Rahul Singh
Rahul Singh

Reputation: 1632

Javascript with regex

I am writing a javascript code usign regex such that it validate license plate. I want a pater for my license plate is 6-8 digit that is not more than 8 and not less than 6 it would be 6 or 7 or 8. But digit should be alphanumeric so I tried function as.

<!----------LICENSE PLATE---------->
var strFilter = /^[A-Za-z0-9]$/;
var obj = document.getElementById("licenseplate");

if ((!strFilter.test(obj)) || (obj.length < 6) || (obj.length > 8)){
    alert("Please enter valid 6-8 digit license plate.");
    obj.focus();
    obj.style.background = "#DFE32D";
    obj.value = "";
    return false;
}

It gives me error on all condition that if all are numeric or all are alphabetic or are combination of both.

Upvotes: 0

Views: 621

Answers (2)

勿绮语
勿绮语

Reputation: 9320

Something like:

/^[0-9A-Za-z]{6,8}$/

Upvotes: 3

smendola
smendola

Reputation: 2311

obj.length is not right... obj, as returned by document.getElementById() is a DOM node, not a String. Assuming licenseplate is a form field:

var strFilter = /^[0-9A-Za-z]{6,8}$/;
var obj = document.getElementById("licenseplate");
if (!strFilter.test(obj.value)) {
    alert("Please enter valid 6-8 digit license plate.");
    obj.focus();
    obj.style.background = "#DFE32D";
    obj.value = "";
    return false;
}

This works.

Upvotes: 1

Related Questions