user1281921
user1281921

Reputation: 163

Javascript function validator

im trying to create a javascript classroom validator that checks if the user enters a valid classroom number.

Rules: Must be 4 digits Must be in the format of: 2 Capital Leters followed by 2 digits

What i have so far. this only checks for the length. im not sure how to go about doing the other validator.

function classRoom_validate(CLASS, max)
{
    var CLASS_len = CLASS.value.length;
    if (CLASS_len != max && CLASS.value.match()
{
    alert("Invalid classroom");
    CLASS.focus();
    return false;
}
return true;
}

Upvotes: 0

Views: 74

Answers (2)

bevacqua
bevacqua

Reputation: 48476

Use a Regex like this:

/[A-Z]{2}[0-9]{2}/.test(code);

/[A-Z]{2}[0-9]{2}/.test("AA12"); // true
/[A-Z]{2}[0-9]{2}/.test("Ab12"); // false
/[A-Z]{2}[0-9]{2}/.test("Abc2"); // false

etc

Upvotes: 1

Collin Green
Collin Green

Reputation: 2196

You need a regular expression:

r = /[A-Z][A-Z]\d\d/

r.test('AA21')
true

r.test('blah')
false

Upvotes: 3

Related Questions