How to add custom validations to fields programmatically?

You can add custom validation to all the user registration fields. For e.g. this code will return an error message if the input field value contains any number.

add_action( 'user_registration_validate_text','ur_validate_text_field',10,4);
function ur_validate_text_field($single_form_field, $data, $filter_hook, $form_id) {	
	$field_label = isset( $data->label ) ? $data->label : '';
	$value = isset( $data->value ) ? $data->value : '';

	if( 1 === preg_match('~[0-9]~', $value ) ) {
	    add_filter( $filter_hook, function ( $msg ) use ( $field_label ) {
	        return __( $field_label . 'should not contain a  number.', 'user-registration' );

1. The above example will work only for the text field.
2. The validation rule defined in the above example restricts users from entering a number into the text field.

If you want custom validation for a different field then,
1. Replace the word “text” in the above code with the field name of the field you want to validate. You can find the field name of the field by clicking on the field in form builder. See screenshot for reference:

2. After replacing it, now the custom validation for the field you selected will work. But the rule will be same. You can change the validation rules as per your convenience or to whatever you want. You can make changes inside the defined function.

Powered by BetterDocs