Apply custom validation to a field

You can use UM action hooks to apply custom validations and rules for any fields and stop forms from being submitted until the conditions are met. We check that the username field does not have the word admin in this example.

add_action('um_submit_form_errors_hook_','um_custom_validate_username', 999, 1);
function um_custom_validate_username( $args ) {
	
	if ( isset( $args['user_login'] ) && strstr( $args['user_login'], 'admin' ) ) {
		UM()->form()->add_error( 'user_login', 'Your username must not contain the word admin.' );
	}
}

You also can select "Custom Validation" and add your "Custom Action" PHP code to the functions.php file in the active theme directory.

Use hook um_custom_field_validation_{$custom} to attach "Custom Action" PHP code.

Code example:

/**
 * Validate field Mobile Number
 * @param string $key
 * @param attay  $array
 * @param array  $args
 */
function um_custom_validate_mobile_number( $key, $array, $args ) {
	if ( isset( $args[$key] ) && !preg_match('/^[6-9]\d{9}$/', $args[$key]) ) {
		UM()->form()->add_error( $key, __( 'Please enter valid Mobile Number.', 'ultimate-member' ) );
	}
}
add_action( 'um_custom_field_validation_mobile_number', 'um_custom_validate_mobile_number', 30, 3 );

Screenshots:

[Ultimate Member > Forms > Edit Form > Edit Field]

Profile form, Error message

Custom Validating Two Fields

The example code below will help you validate and compare two fields, we use "user_login" & "nickname" as examples.
The user will get an error if the values in both fields are the same.

Code example:

add_action('um_submit_form_errors_hook_', 'um_custom_validate_username_nickname', 999, 1);

function um_custom_validate_username_nickname( $args ) {
	
	if ( isset( $args['user_login'] ) && isset( $args['nickname'] ) && $args['user_login'] == $args['nickname'] ) {
		UM()->form()->add_error( 'user_login', 'Your username and nickname can not be equal.' );
	}
}


Register Form, Error Message

The second example with the Custom Validation set to username_nickname for the Nickname UM Forms Designer field.

Code example:

function um_custom_validate_username_nickname( $key, $array, $args ) {

	if ( isset( $args[$key] ) && isset( $args['user_login'] ) && $args[$key] == $args['user_login'] ) {
		UM()->form()->add_error( $key, __( 'Your username and nickname can not be equal.', 'ultimate-member' ) );
	}
}
add_action( 'um_custom_field_validation_username_nickname', 'um_custom_validate_username_nickname', 30, 3 );


Screenshots:

[Ultimate Member > Forms > Edit Form > Edit Field]


Register Form, Error Message

Note: Try adding the code snippet to your theme’s functions.php file or use the Code Snippets plugin.