validating variable in javascript
Hi i have a fi开发者_开发知识库eld in php that will be validated in javascript using i.e for emails
var emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
What i'm after is a validation check which will look for the first letter as a capital Q then the next letters can be numbers only then followed by a . then two numbers only and then an optional letter i.e Q100.11 or Q100.11a
I must admit i look at the above email validation check and i have no clue how it works but it does ;)
many thanks for any help on this
Steve
The ^
marks the beginning of the string, $
matches the end of the string. In other words, the whole string should exactly match this regular expression.
[\w-\.]+
: I think you wanted to match letters, digits, dots and-
only. In that case, the-
should be escaped (\-
):[\w\-\.]+
. The plus-sign makes is match one or more times.@
: a literal@
match([\w-]+\.)+
letters, digits and-
are allowed one or more times, with a dot after it (between the parentheses). This may occur several times (at least once).[\w-]{2,4}
: this should match the TLD, likecom
,net
ororg
. Because a TLD can only contain letters, it should be replaced by[a-z]{2,4}
. This means: lowercase letters may occur two till four times. Note that the TLD can be longer than 4 characters.
An regular expression which should follow the next rules:
- a capital
Q
(Q
) - followed by one or more occurrences of digits (
\d+
) - a literal dot (
.
) - two digits (
\d{2}
) - one optional letter (
[a-z]?
)
Result:
var regex = /Q\d+\.\d{2}[a-z]?/;
If you need to match strings case-insensitive, add the i
(case-insensitive) modifier:
var regex = /Q\d+\.\d{2}[a-z]?/i;
Validating a string using a regexp can be done in several ways, one of them:
if (regex.test(str)) {
// success
} else {
// no match
}
var emailRegex = /^Q\d+\.\d{2}[a-zA-Z]?@([\w-]+\.)+[a-zA-Z]+$/;
var str = "Q100.11@test.com";
alert(emailRegex.test(str));
var regex = /^Q[0-9]+\.[0-9]{2}[a-z]?$/;
+
means one or more
the period must be escaped - \.
[0-9]{2}
means 2 digits, same as \d{2}
[a-z]?
means 0 or 1 letter
You can check your regex at http://regexpal.com/
精彩评论