Steven Kinnear
Steven Kinnear

Reputation: 412

validating variable in javascript

Hi i have a field 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

Upvotes: 1

Views: 1748

Answers (3)

mkruzil
mkruzil

Reputation: 750

var emailRegex = /^Q\d+\.\d{2}[a-zA-Z]?@([\w-]+\.)+[a-zA-Z]+$/;
var str = "[email protected]";
alert(emailRegex.test(str));

Upvotes: 1

Lekensteyn
Lekensteyn

Reputation: 66415

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, like com, net or org. 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
}

Upvotes: 2

foson
foson

Reputation: 10227

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/

Upvotes: -1

Related Questions