【问题标题】:wordpress field validation with regex使用正则表达式验证 wordpress 字段
【发布时间】:2021-11-28 12:05:48
【问题描述】:

我使用 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' );

现在我需要使用正则表达式验证该字段,如下所示:

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

当前字段验证不能为空。如果有人能帮忙,我将不胜感激

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

【问题讨论】:

    标签: php regex wordpress validation woocommerce


    【解决方案1】:

    使用preg_match:

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

    【讨论】:

    • 感谢您的帮助。出于某种原因,我用您的代码替换了 'if ( isset( $_POST['billing_first_name']' 并且它通过了没有任何验证。
    • 找到了解决方案。需要添加 !preg_match
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多