1

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?

hyphen
  • 2,368
  • 5
  • 28
  • 59

1 Answers1

4

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"/>
Shahar Shokrani
  • 7,598
  • 9
  • 48
  • 91
  • Perfect! Thank you! – hyphen Feb 21 '19 at 09:02
  • The problem with MaxLength="10" is when they enter in the following format: 333-222-1111, it will leave last two digits out and give warning ... many people use dashes, parentheses and other dividers when entering phone numbers... also in US, many people with start with 1 (country code) ... – Levchik Aug 06 '19 at 15:35