Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression which allows numbers, spaces, plus sign, hyphen and brackets

Tags:

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.  }, } 
like image 883
StreetCoder Avatar asked Dec 30 '14 08:12

StreetCoder


People also ask

What is ?! In regex?

It's a negative lookahead, which means that for the expression to match, the part within (?!...) must not match. In this case the regex matches http:// only when it is not followed by the current host name (roughly, see Thilo's comment).

What is the syntax to define a regular expression?

Writing a regular expression pattern. A regular expression pattern is composed of simple characters, such as /abc/ , or a combination of simple and special characters, such as /ab*c/ or /Chapter (\d+)\.\d*/ . The last example includes parentheses, which are used as a memory device.


1 Answers

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]*$/ 
like image 133
nu11p01n73R Avatar answered Nov 12 '22 07:11

nu11p01n73R