jQuery phone number validation allow spaces, minimum of 8 digits

孤人 提交于 2019-11-27 07:54:28

问题


How can I allow spaces within an a numbers only validation, with a minimum of 8 digits? Phone numbers are much easier to type in when spaces are allowed. e.g. 0400 123 456, 9699 1234.

Here's my code so far, I've only got the minimum 8 digits validation working:

jQuery.validator.addMethod(
  "phone",
  function(phone_number, element) {
    return this.optional(element) || /^\d{8}$/.test(phone_number);
  },
    "Please enter numbers only"
);

回答1:


Remove the space before validating:

return this.optional(element) || /^\d{8,}$/.test(phone_number.replace(/\s/g, ''));

This way you retain the space




回答2:


My suggestion is to just remove the spaces from the phone_number before validating.

jQuery.validator.addMethod(
  "phone",
  function(phone_number, element) {
    return this.optional(element) || /^\d{8}$/ *$/.test(phone_number.replace(/\s/g, ""));
  },
    "Please enter numbers only"
);


来源:https://stackoverflow.com/questions/11025587/jquery-phone-number-validation-allow-spaces-minimum-of-8-digits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!