jQuery 验证插件问题不适用于数字字段

jQuery validation plugin issue not working for number field

我正在使用 jQuery 验证插件,它部分有效。验证电子邮件字段没有问题(输入时显示两个错误的电子邮件)但 phone 数字字段未得到验证。

它显示消息 "Please enter the mobile number" 但不显示 "Please enter valid mobile number"

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
var $emailPreferenceForm = $('#email-preference__form');

function emailPreferenceFormValidate() {
    $emailPreferenceForm.validate({
        rules: {

            emailaddress: {
                required: true,
                //email: true
                myEmail: true
            },
            phonenumber: {
                minlength: 10,
                maxlength: 10,
                digits: true,
                myPhone: true
            }
        },
        messages: {
            emailaddress: "Please use a valid e-mail address",
            phonenumber: "Please enter the mobile number"
        }
    });
}

jQuery.validator.addMethod("myEmail", function(value, element) {
    return this.optional( element ) || ( /^[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,4}$/.test( value ) && /^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*/.test( value ) );
}, 'Please enter valid email address.');

jQuery.validator.addMethod("myPhone", function(value, element) {
    return this.optional( element ) || /^[0-9]*$/.test( value );
}, 'Please enter valid mobile number.');

emailPreferenceFormValidate();

/**/

$("#email-preference__form input").on('click',function() {

    userPrefs_newsletters = $("input#newsletters_emailpref").is(':checked');
    userPrefs_newsletters_phone = $("input#newsletters_phonepref").is(':checked');

    userPrefs_lease_information = $("input#lease_information_emailpref").is(':checked');
    userPrefs_lease_information_phone = $("input#lease_information_phonepref").is(':checked');

    userPrefs_buying_information = $("input#buying_information_emailpref").is(':checked');
    userPrefs_buying_information_phone = $("input#buying_information_phonepref").is(':checked');

    userPrefs_special_offer = $("input#special_offer_emailpref").is(':checked');
    userPrefs_special_offer_phone = $("input#special_offer_phonepref").is(':checked');

    $("#email-preference__form button[type='button']").removeAttr("disabled"); // enable the Submit button
});

function postData() {
    var phoneNumber = $('#phonenumber').val();
    if(!phoneNumber && (userPrefs_special_offer_phone || userPrefs_lease_information_phone || userPrefs_buying_information_phone || userPrefs_newsletters_phone)){
        alert("Please enter the phone number to opt in for text notifications");
    } else{
        console.log("postData:"+ "123");


    // });

    }
}
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.1/dist/jquery.validate.min.js"></script>
<div class="row   section-container-toppadding section-container-bottompadding clearfix columnctrl">
  <div class="row">
    <div>
      <div class="col-md-12 col-sm-12 col-xs-12">
        <div class="row unsubscribe-section mb50">
          <!-- View 1: Preferences -->
          <div class="col-md-12">
            <h2 class="pref-heading">Notification Preference Center</h2>
          </div>
          <div>
            <div class="col-md-12 col-sm-12 col-xs-12 preferences">
              <p class="lead col-md-12 col-lg-7 p0 pt10 pb40 m0"> Get the notifications you want and need. Please choose the options below that best fit your needs.</p>
              <form id="email-preference__form" novalidate="novalidate" action="/en-us/email-preference-center-thankyou.html" method="get" class="preference-form">
                <div class="row preference-form--contactinfo col-lg-8">
                  <!-- Email Address -->
                  <div class="col-md-5 col-sm-7 col-xs-12 p0 col-lg-6">
                    <div class="form-group">
                      <label for="emailaddress">Email Address</label>
                      <input data-minlength="3" placeholder="Label" value="" id="emailaddress" name="emailaddress" type="text" required="" class="valid" aria-invalid="false"><label id="emailaddress-error" class="error" for="emailaddress" style="display: none;"></label>
                    </div>
                  </div>
                  <!-- Phone Number -->
                  <div class="col-md-5 col-sm-7 col-xs-12 p0 col-lg-6">
                    <div class="form-group">
                      <label for="phonenumber">Phone Number</label>
                      <input data-minlength="10" data-msg-required="Please enter something here!" placeholder="Label" value="" id="phonenumber" name="phonenumber" type="number" class="valid" aria-invalid="false"><label id="phonenumber-error" class="error"
                        for="phonenumber" style="display: none;"></label>
                    </div>
                  </div>
                </div>
                <div class="choices pt20 pb20 mt10">
                  <div class="row choices-mob__header">
                    <div class="col-md-12 col-sm-12 col-xs-12 hidden-xs">
                      <div class="col-sm-8"></div>
                      <div class="checkbox-wrapper col-sm-4 p0">
                        <div class="col-sm-6 pl0">Email</div>
                        <div class="col-sm-6 pl0">Text</div>
                      </div>
                    </div>
                  </div>
                  <div class="row choices--contents ml0 mr0 mb20 pb20">
                    <div class="col-md-12 col-sm-12 col-xs-12 pl0 pr0">
                      <div class="form-group col-sm-8 p0">
                        <div class="checkbox-ios-v2">
                          <div class="checkbox-ios-v2-copy">
                            <h5>GM Financial Newsletter &amp; Announcements</h5>
                            <p> Be the first to receive tips on auto finance basics.</p>
                          </div>
                        </div>
                      </div>
                      <div class="checkbox-wrapper col-sm-4 p0">
                        <div class="col-sm-6 pl0">
                          <div class="checkbox">
                            <input autocomplete="off" type="checkbox" name="newsletters_emailpref"                                    id="newsletters_emailpref" class="valid">
                            <label class="checkbox-check" tabindex="0"                                                             for="newsletters_emailpref">Email</label>
                          </div>
                        </div>
                        <div class="col-sm-6 pl0">
                          <div class="checkbox">
                            <input autocomplete="off" type="checkbox" name="newsletters_phonepref"                                   id="newsletters_phonepref" class="valid">
                            <label class="checkbox-check" tabindex="0"                                                             for="newsletters_phonepref">Text</label>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>             
                </div>
                <div class="row submit-btn mb60">
                  <div class="col-sm-4 col-xs-12">
                    <!-- <button type="submit">Submit</button> -->
                    <button type="button" class="btn btn-primary" onclick="postData()">SAVE</button>
                  </div>
                </div>

              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

It shows the message "Please enter the mobile number" but not the "Please enter valid mobile number".

嗯,那是因为你压倒了这里的一切...

messages: {
    phonenumber: "Please enter the mobile number" // <- for ALL rules
}

您告诉它在 phonenumber 字段上为所有验证规则使用相同的消息。

如果您想要特定规则的特定消息,那么您需要构建 messages 选项...

messages: {
    phonenumber: {
        minlength: "Please enter the mobile number with at least {0} digits",
        maxlength: "Please enter the mobile number with less than {0} digits",
        digits: "Please enter only digits for the mobile number",
        // myPhone: // uses the message from .addMethod()
    }
}

你会 省略 myPhone 的任何内容,因为自定义消息已经在 .addMethod("myPhone").

中定义