User Registration

Step by step documentation to set up a user registration form for your website.

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) {    
  $label = $single_form_field->general_setting->field_name;
    $value = isset( $data->value ) ? $data->value : '';
    if( 'input_box_1650861331' === $single_form_field->general_setting->field_name ) {
        if( 1 === preg_match('~[0-9]~', $value ) ) {
      $message = array(
        /* translators: %s - validation message */
        $label       => __( 'Value should not contain a  number', 'user-registration' ),
        'individual' => true,
      );
      add_filter(
        $filter_hook,
        function ( $msg ) use ( $message, $form_data ) {
          $message = apply_filters( 'user_registration_modify_field_validation_response', $message, $form_data );
          return $message;
        }
      );
        }
    }
}

Create a custom validation based on the above codes #

NOTE:

  1. The above example will work only for the input field.
  2. You must replace the ‘input_box_1650861331’ with the field name of the respective field.
  3. 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 the form builder. See the screenshot for reference:

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

Note: Please visit this documentation to add the custom codes in your site.

Powered by BetterDocs

Scroll to top