Home > Software design >  wordpress field validation with regex
wordpress field validation with regex

Time:10-09

I created a new field in the registration form using this code in functions.php :

function wooc_extra_register_fields() {?>
     
       <p class="form-row form-row-wide">
       <label for="reg_billing_first_name"><?php _e( 'Bitcoin Refund Address', 'woocommerce' ); ?><span class="required">*</span></label>
       <input type="text" class="input-text" name="billing_first_name" id="reg_billing_first_name" value="<?php if ( ! empty( $_POST['billing_first_name'] ) ) esc_attr_e( $_POST['billing_first_name'] ); ?>" />
       </p>
     
       <div class="clear"></div>
       <?php
 }
 add_action( 'woocommerce_register_form_start', 'wooc_extra_register_fields' );

Now I need to validate that field with a regex expression as follows:

^(bc1|[13])[a-zA-HJ-NP-Z0-9]{25,39}$

The current field validation is just not to be empty. If anyone can help i'd really appreciate it

function wooc_validate_extra_register_fields( $username, $email, $validation_errors ) {
      if ( isset( $_POST['billing_first_name'] ) && empty( $_POST['billing_first_name'] ) ) {
             $validation_errors->add( 'billing_first_name_error', __( 'Refund Address is required!', 'woocommerce' ) );
      }
    
         return $validation_errors;
}
add_action( 'woocommerce_register_post', 'wooc_validate_extra_register_fields', 10, 3 );

CodePudding user response:

Use preg_match:

if ( preg_match( '/^(bc1|[13])[a-zA-HJ-NP-Z0-9]{25,39}$/', $_POST['billing_first_name'] ) ) {...}
  • Related