开发者

How do I use regex to perform a validation?

开发者 https://www.devze.com 2023-01-23 11:01 出处:网络
I\'d like to evaluate a form field using a regex. What expression do I use to actually compare t开发者_如何学Pythonhe value to the regex?

I'd like to evaluate a form field using a regex.

What expression do I use to actually compare t开发者_如何学Pythonhe value to the regex?

I'm imagining something thus:

if($('#someID').val() == /someregex/) {doSomething()}

But that doesn't work. Any advice?


Use

if (/^someregex$/.test($('someID').value()) {
     // match
} else {
     // no match
}


Note that there is no value() method in jQuery, you need to use val() and match like this:

if($('#someID').val().match(/someregex/) {
  // success
}

More Info:

  • http://www.regular-expressions.info/javascript.html


use the match method of the strings..

string.match(regexp)

so in your case

if( $('#someID').value().match(/someregex/) ) {doSomething()}


I think you're looking for .test():

var myRegex = /someregex/;
if ( myRegex.test($('#someID').value()) ) {
    doSomething();
}

You can use exec() to check it and get an array of it's matches, or match() from the string object.


We don't compare values to regular expressions. We use regular expressions to test if a value matches a pattern.


Something like:

if (/myRegExp/.test($('#myID').val()) { 
  //... do whatever 
}

see http://www.evolt.org/regexp_in_javascript

0

精彩评论

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