开发者

Jquery validate: Regexing a non-US phonenumber

I'm using this:

jQuery.validator.addMethod("regex2", function(value, element, param) {
  return value.match(new RegExp("." + param + "$"));
});

$("#phonenumbe开发者_如何学Cr").rules("add", { regex2: "[0-9]+"})

to validate a phone. The phone number must be at least 7 digits long, the I got this regex from elsewhere and am using the parameter minlength=7, but this is obviously unsuitable. How should this validation be done?

I live in Venezuela. So I think this is useless. How can I change it? In my country 0416-414 33 44 should be considered a valid input for a phone number.


Assuming:

  • The space character can be any whitespace.
  • The space is optional.
  • There can be more than one space.
  • There must be at least seven digits.

Then change "[0-9]+" to "[0-9]{7,}\s*$".

It also seems that the "." is incorrect and should be a "^".


You may find the following regex useful, it basically first strips all valid special characters which a phone number anywhere in the world can contain (spaces, parens, +, -, ., ext) and then counts the digits if there are at least 7.

$.validator.addMethod('phone', function(value, element) {
    return this.optional(element) || (/^\d{7,}$/).test(value.replace(/[\s()+\-\.]|ext/gi, ''));
});

Use it with <input class="phone">.


Are you sure about that . at the front of the regex? I wonder if that's supposed to be a caret ^ which is counterpart to $: it anchors the regex so the entire string must match the regex.

You could add spaces to the regex, but a more elegant solution would be to trim it first. Trimming a string removes whitespace from the beginning and end. Either of these will work:

// Trim value before matching against regex.
return jQuery.trim(value).match(new RegExp("^" + param + "$"));

// Allow spaces at beginning or end with " *" (space + asterisk).
return value.match(new RegExp("^ *" + param + " *$"));

Also, while we're at it you could make this a bit more robust by adding parentheses around param.

// Add parentheses for robustness.
return jQuery.trim(value).match(new RegExp("^(?:" + param + ")$"));

That way your new regex will work even if param is, say, this|that. You'd want to match ^(this|that)$ rather than ^this|that$, since the latter would be equivalent to the incorrect (^this)|(that$).


You cant first trim and then validate, or just add a \s? before the $ in this line:

  return value.match(new RegExp("." + param + "$"));

Change the ? for a * to accept more than one blank

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜