How do I use regex to perform a validation? - javascript

I'd like to evaluate a form field using a regex.
What expression do I use to actually compare the 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

Related

Why is this regular expression in javascript still allowing special characters [a-zA-Z1-9 ]?

I don't want to allow special characters but this regular expression still allows them, what am I doing wrong?
When i type for name : '&é"é&'é"&'&é"'a' It still gives back 'true'
name.match(/[a-zA-Z1-9 ]/))
You need to use RegExp#test with anchors ^ and $.
/^[a-zA-Z1-9 ]+$/.test(name)
String#match return an array if match is found. In your case, a at the end of the string is found and array is returned. And array is truthy in the Javascript. I believe, the array is converted to Boolean, so it returned true.
It returns true because the last character ('a') is ok. Your regex doesn't check whether the complete input matches the regex.
Try this one:
^[a-zA-Z1-9 ]*$
if(!/[^a-zA-Z0-9]/.test(name)) {
// "your validation message"
}
try this
This will work for you:
var nameregex = /^([A-Za-z0-9 ]$)/;
var name = document.getElementById('name').value;
if (!name.match(nameregex)) {
alert('Enter Valid Name!!');
}

Javascript match one regex, but not another

How can I find all words in string which
match one expression:
/[a-zA-Z]{4,}/
but do not match another one:
/\b[a-zA-Z]([a-zA-Z])\1+[a-zA-Z]\b/
Something like pseudocode:
string.match( (first_expression) && ( ! second_expression) )
You could just do this:
string.match(/[a-zA-Z]{4,}/) && !string.match(/\b[a-zA-Z]([a-zA-Z])\1+[a-zA-Z]\b/)
But if you'd like to combine the patterns, you can use a negative lookahead ((?!...)), like this:
string.match(/^(?!.*\b[a-zA-Z]([a-zA-Z])\1+[a-zA-Z]\b).*[a-zA-Z]{4,}.*$/)
But this will reject the whole string if it finds the second pattern—e.g."fooz barz" will return null.
To ensure the words you find do not match the other pattern, try this:
string.match(/\b(?![a-zA-Z]([a-zA-Z])\1+[a-zA-Z]\b)[a-zA-Z]{4,}\b/)
In this case, "fooz barz" will return "barz".
Note that this can be cleaned up a bit by using the case insensitive flag (i):
string.match(/\b(?![a-z]([a-z])\1+[a-z]\b)[a-z]{4,}\b/i)
if(string.match(first_expression))
{
if(!string.match(second_expression))
{
//Do something important
}
}
This should match what you want and not what you don't.

Determine Whether String Begins With Particular Letters

I am trying to determine using javascript and regex whether a string begins with certain letters. If it's true I want it do something. I am trying to find the value "window_" in a particular string.
My code is as follows:
if (div_type.match(/^\window_/)){
}
This however is returning true when it clearly doesn't contain it.
Regular expressions are overkill for this kind of string matching:
if (div_type.indexOf("window_") === 0) {
// Do something
}
If you really want to go the regex route, you can use test() instead of match() /regex_pattern/.test(string)
Example:
function run(p){
return /^window_/.test(p);
}
console.log(run("window_boo"), // true
run("findow_bar")); // false
Your use:
if ( /^window_/.test(div_type) ) {
...
}
You don't need a regex for that.
if( div_type.substr(0,"window_".length) == "window_")

Using variable in a regex

say i have the following variables:
myId; //Email_PDF
currentHoverOnItem; //Email_PDF_english of Email_PDF_Dutch or ...
So the first value is "Email_PDF" and the second is "Email_PDF_english". What i want i when currentHoverOnItem contains myId, then something can be executed.
This is what i have so far:
var pattern = new RegExp("^/"+myId+"/$");
if (currentHoverOnItem.match(pattern))
{
//Do something
}
Is this the right way to use the regex? It should match part of the string, there can be text before or after the match.
Is this the right way to use the regex?
No! Regexes are for patterns, not for literal strings. Use indexOf
if (currentHoverOnItem.indexOf(myId) >= 0)
{
//Do something
}
Try this
var pattern = new RegExp(myId, "g");
if (currentHoverOnItem.match(pattern))
{
//Do something
}
Your pattern is "anchored", meaning that ^ and $ specifiy begin and end of your string.
To match "Email_PDF_english" in an anchored pattern you could use
^Email_PDF_(.*)$, but it won't match if your string is longer, as your comment suggests.
If it's not anchored you could test for a blank following the Email_PDF_... string, ie
Email_PDF_([^\s]*)\s+
You need not use a reg_exp here. Using indexOf will do the trick for you
if(currentHoverOnItem.indexOf(myId) != -1)
{
//Do something
}

Javascript wildcard variable?

The value of product_id might be some combination of letters and numbers, like: GB47NTQQ.
I want to check to see if all but the 3rd and 4th characters are the same.
Something like:
if product_id = GBxxNTQQ //where x could be any number or letter.
//do things
else
//do other things
How can I accomplish this with JavaScript?
Use regular expression and string.match(). Periods are single wildcard characters.
string.match(/GB..NTQQ/);
Use a regular expression match:
if ('GB47NTQQ'.match(/^GB..NTQQ$/)) {
// yes, matches
}
Answers so far have suggested match, but test is likely more appropriate as it returns true or false, whereas match returns null or an array of matches so requires (implicit) type conversion of the result within the condition.
if (/GB..NTQQ/.test(product_id)) {
...
}
if (myString.match(/regex/)) { /*Success!*/ }
You can find more information here: http://www.regular-expressions.info/javascript.html

Categories