i have jquery validation plugin on page. when types phone number form field, want validator recognize format (ru):
+#(###)-###-##-## or +#-###-###-#### or +#-###-###-##-## or +###########
i have in .js file:
$.validator.addmethod('customphone', function (value, element) { return this.optional(element) || /^\+d{1}(\d{3})\d{7}$/.test(value); }, "please enter valid phone number"); $(document).ready(function() { $('form').validate({ rules: { phone: 'customphone' } ...
this not working me, see why? or there better way this? :)
you need following regex:
/^\+(?:\d(?:\(\d{3}\)|-\d{3})-\d{3}-(?:\d{2}-\d{2}|\d{4})|\d{11})$/
see regex demo
the regex have ^\+d{1}(\d{3})\d{7}$
has d
instead of \d
(thus failing match digits) , unescaped parentheses (thus pattern did not match literal parentheses).
breakdown:
^
- start of string\+
- literal+
symbol(?:\d(?:\(\d{3}\)|-\d{3})-\d{3}-(?:\d{2}-\d{2}|\d{4})|\d{11})
- 2 alternatives:\d(?:\(\d{3}\)|-\d{3})-\d{3}-(?:\d{2}-\d{2}|\d{4})
:\d
- digit(?:\(\d{3}\)|-\d{3})
- either(123)
substring or-123
substring-\d{3}
- hyphen followed 3 digits-
- hyphen(?:\d{2}-\d{2}|\d{4})
- 2 digits followed hyphen , 2 digits or 4 digits
|
- or\d{11}
- 11 digits
$
- end of string
Comments
Post a Comment