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' );
	   });
	}
}

Powered by BetterDocs