javascriptjqueryregexjquery-plugins

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


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.
 },
}

Solution

  • You can add the required characters into a character class:

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

    Regex Demo

    Regex Explanation

    OR

    If you are reluctant to use lookaheads you could write a longer regex:

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