简体   繁体   中英

parsley.js optionally validate number input

I have an input field for a phone number. It's an optional field on the form, but if it's populated it needs to be 10 digits. So, either empty, or 10 digits. How can I accomplish this using parsley.js?

this question is similar to what I'm looking for, but I've tried various combinations and it's not working:

enter link description here

here's my input:

<input type="text" class="form-control form-control-sm m-input phone-num" autocomplete="off" style="display:none;" id="phone-input" name="phone" placeholder="0" data-parsley-trigger="keyup" data-parsley-validation-threshold="1" data-parsley-debounce="500" data-parsley-type="digits">

and this is the parsley initialization (validation is working for other fields on the same form, so I don't think this is the problem):

    $('#myForm').parsley({
      trigger: 'keyup',
      classHandler: function(el){
        return el.$element.closest('.form-group');
      },
      errorClass: 'has-danger',
      errorsWrapper: '<div class="form-control-feedback"></div>',
      errorTemplate: '<span></span>'
    });

Would a custom validation be needed for this? If so, how can I accomplish that?

Just add to the input an attribute of data-parsley-type="digits" and data-parsley-minlength="10" data-parsley-maxlength="10" .

Example:

<input type="text" class="form-control form-control-sm m-input phone-num" autocomplete="off" 
    style="display:none;" id="phone-input" 
    name="phone" placeholder="0" data-parsley-trigger="keyup" data-parsley-validation-threshold="1" 
    data-parsley-debounce="500" 
    data-parsley-type="digits" 
    data-parsley-minlength="10" 
    data-parsley-maxlength="10"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM