Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
180
rated 0 times [  184] [ 4]  / answers: 1 / hits: 50392  / 10 Years ago, tue, december 30, 2014, 12:00:00

I am using jquery validator where I have added a method to validate a string which allow only numbers, spaces, plus sign, hyphen and brackets. Number is mandatory in the string but other charterer is optional.



My code for adding method in jquery validor:



jQuery.validator.addMethod( regex, function(value, element, regexp) {
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
Please check your input.
);


Following code for the rules:



rules: {
myfield: {
required: true,
regex: [0-9]+ // want to add regular expression but I wrote only for digit which works but do not understand how to reach at my requirements.
},
}

More From » jquery

 Answers
3

You can add the required characters into character class as



/^(?=.*[0-9])[- +()0-9]+$/


Regex Demo



Regex Explanation




  • (?=.*[0-9]) postive look ahead. Ensures that there is atleast one digit


  • [- +()0-9]+ matches numbers, spaces, plus sign, hyphen and brackets




OR



If you are reluctant in using look aheads. You could write without them a lenghier regex as



/^[- +()]*[0-9][- +()0-9]*$/

[#68356] Thursday, December 25, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
paola

Total Points: 675
Total Questions: 115
Total Answers: 95

Location: Laos
Member since Tue, Jul 7, 2020
4 Years ago
;