regex for serial number in javascript - javascript

var serialNumber = $('#SerialNumber').val();
var serialNumberPattern = new RegExp('^[\s\da-zA-z\-.]+$');
if (!serialNumberPattern.test(serialNumber)) {
}
Above is the code I am using to validate a serial number which has alphanumeric characters, dots (.), dashes (-), and slashes (/) in it but somehow it's not working. Where am I going wrong? Please help.

When you're passing regex to RegExp constructor which uses " as regex delimiter, you have to escape all the backslashes one more time. Or otherwise it would be treated as an escape sequence.
var serialNumberPattern = new RegExp("^[\\s\\da-zA-Z.-]+$");
alphanumeric,dot(.),Dash(-),Slash(/) in it.
var serialNumberPattern = new RegExp("^[\\da-zA-Z./-]+$");

Just use /^[\s\da-zA-Z\-.\/]+$/, it's simple and works just fine.
You should only use the RegExp constructor when parts of the expression use a variable. This is not true in your case and just adds additional confusion.
document.write(/^[\s\da-zA-Z\-.\/]+$/.test('23 43-89'))

Related

Regarding double escaping characters when using regexp constructor with a string to make a regexp

In Javascript, I want to match a string pattern that goes something like:
\left((some expression here to be matched)\right)
It's a little more complicated than that, so I have to define my pattern using the RegExp constructor. The simplified version is:
var pattern_string = '\\left\\((' + EXPRESSIONpattern + ')\\\\right\\)' ;
var pattern_regexp = new RegExp(pattern_string, 'g');
I realize that \r is the carriage return character in a string, hence having the four back slashes in the pattern_string before the r. Upon implementing, the only way I could get it to work was to also treat \l as a special string character and use:
var pattern_string = '\\\\left\\((' + EXPRESSIONpattern + '\\\\right\\)' ;
var pattern_regexp = new RegExp(pattern_string, 'g');
Why do I need to double escape the l? I can't find a reference that says \l is a special string sequence. What does \l mean in a string? Can someone point me to a reference that includes all characters that need to be double escaped in a string? It would help greatly with debugging to know for sure when I need to double escape.
Thanks in advance for your help,
T

javascript regex to require at least one special character

I've seen plenty of regex examples that will not allow any special characters. I need one that requires at least one special character.
I'm looking at a C# regex
var regexItem = new Regex("^[a-zA-Z0-9 ]*$");
Can this be converted to use with javascript? Do I need to escape any of the characters?
Based an example I have built this so far:
var regex = "^[a-zA-Z0-9 ]*$";
//Must have one special character
if (regex.exec(resetPassword)) {
isValid = false;
$('#vsResetPassword').append('Password must contain at least 1 special character.');
}
Can someone please identify my error, or guide me down a more efficient path? The error I'm currently getting is that regex has no 'exec' method
Your problem is that "^[a-zA-Z0-9 ]*$" is a string, and you need a regex:
var regex = /^[a-zA-Z0-9 ]*$/; // one way
var regex = new RegExp("^[a-zA-Z0-9 ]*$"); // another way
[more information]
Other than that, your code looks fine.
In javascript, regexs are formatted like this:
/^[a-zA-Z0-9 ]*$/
Note that there are no quotation marks and instead you use forward slashes at the beginning and end.
In javascript, you can create a regular expression object two ways.
1) You can use the constructor method with the RegExp object (note the different spelling than what you were using):
var regexItem = new RegExp("^[a-zA-Z0-9 ]*$");
2) You can use the literal syntax built into the language:
var regexItem = /^[a-zA-Z0-9 ]*$/;
The advantage of the second is that you only have to escape a forward slash, you don't have to worry about quotes. The advantage of the first is that you can programmatically construct a string from various parts and then pass it to the RegExp constructor.
Further, the optional flags for the regular expression are passed like this in the two forms:
var regexItem = new RegExp("^[A-Z0-9 ]*$", "i");
var regexItem = /^[A-Z0-9 ]*$/i;
In javascript, it seems to be a more common convention to the user /regex/ method that is built into the parser unless you are dynamically constructing a string or the flags.

Regexp for floating number

I found this regexp for validating floats. But I cant see how 2-1 will accepted. The below evaluates to true. I can't use parseFloat because I need to be able to accept "," instead of "." also. I wrote re2, same result though.
var re1 = new RegExp("^[-+]?[0-9]*\.?[0-9]+$");
console.log(re1.test("2-1"));
var re2 = new RegExp("^([0-9]+)\.([0-9]+)$");
console.log(re2.test("2-1"));
If you generate the regex using the constructor function, you have to to escape the backslash, i.e. \ becomes \\:
var re1 = new RegExp("^[-+]?[0-9]*\\.?[0-9]+$");
Another option is to use the literal syntax which doesn't require escaping:
var re1 = /^[-+]?[0-9]*\.?[0-9]+$/
Sometimes when you create a regex string, you even have to escape the backslash; this can of course be done with a backslash, so the final regex looks something like "\\.*", etc.
Doing this, I was able to get the correct results, as seen here:
var re1 = new RegExp("^[-+]?[0-9]*\\.?[0-9]+$");
console.log(re1.test("2-1"));
var re2 = new RegExp("^([0-9]+)\\.([0-9]+)$");
console.log(re2.test("2-1"));
console.log(re1.test("2.1"));
console.log(re2.test("2.1"));​
What about replacing a comma (",") with a period (".") and then using parseFloat?

RegExp.test not working?

I am trying to validate year using Regex.test in javascript, but no able to figure out why its returning false.
var regEx = new RegExp("^(19|20)[\d]{2,2}$");
regEx.test(inputValue) returns false for input value 1981, 2007
Thanks
As you're creating a RegExp object using a string expression, you need to double the backslashes so they escape properly. Also [\d]{2,2} can be simplified to \d\d:
var regEx = new RegExp("^(19|20)\\d\\d$");
Or better yet use a regex literal to avoid doubling backslashes:
var regEx = /^(19|20)\d\d$/;
Found the REAL issue:
Change your declaration to remove quotes:
var regEx = new RegExp(/^(19|20)[\d]{2,2}$/);
Do you mean
var inputValue = "1981, 2007";
If so, this will fail because the pattern is not matched due to the start string (^) and end string ($) characters.
If you want to capture both years, remove these characters from your pattern and do a global match (with /g)
var regEx = new RegExp(/(?:19|20)\d{2}/g);
var inputValue = "1981, 2007";
var matches = inputValue.match(regEx);
matches will be an array containing all matches.
I've noticed, for reasons I can't explain, sometimes you have to have two \\ in front of the d.
so try [\\d] and see if that helps.

How do I use a regular expression in JavaScript to see if a string begins with a period?

I'm new to regular expressions.
The following code works as expected, printing first "true" and then "false", the backslash in front of the period escaping it:
var pattern = new RegExp(/\./);
document.write(pattern.test("."));
document.write(pattern.test("a"));
But why does the following print "false":
var pattern = new RegExp(/\b\./);
document.write(pattern.test("."));
The period is, after all, at the beginning of the string.
You want to try using ^ -
/^\./
If you have
/\b\./
it matches the .'s in Hello. How are you.
It doesn't work because to have a word break, you first need to have a word.
Using a \b, this would work:
var pattern = new RegExp(/a\b\./);
document.write(pattern.test("a."));
If all you're doing is testing the first character, you can do it without a regex if you'd like.
".".charAt(0) === "."

Categories