Home > database >  Regex simple phone validation with JQuery-validation plugin
Regex simple phone validation with JQuery-validation plugin

Time:06-23

I have a simple contact form. I need a specific regex expression for the phone number. User can type between 5-15 characters. Space, -, and digits are allowed. I have used the below pattern but it doesn't meet my needs.

jQuery.validator.addMethod(
    'phone',
    function (value, element, params) {
      return (
        this.optional(element) ||
        /\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/.test(value)
      );
    },
    'Bitte nur erlaubte Zeichen eingeben: [0-9],  , -'
  );

CodePudding user response:

Add a start ^ and end $

https://regex101.com/r/bIxPK3/4

const re = /^\ ?\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})$/;

function testPhone(value) {
  return re.test(value)
}

console.log(testPhone("01729863834jkjj"))
console.log(testPhone("(555)-555-5553"))
console.log(testPhone("555 555 5553"))
console.log(testPhone(" 555 555 5553"))
console.log(testPhone(" 001 555 1234"))

  • Related