...

View Full Version : Strict JavaScript Validation for Beginner



bill737
06-18-2010, 04:11 PM
Hi, I am fairly new at Javascript but have some ability - though I can't figure this one out.

I need a JavaScipt "IF Statement" that validates that a Text Field is in the format of 2 Letters then 2 Numbers. The field also has to contain a total of 4 characters no matter what.

For example, every entry for that Text Field has to be in the following format: AB34

I would sincerely appreciate anyones help!

Philip M
06-18-2010, 04:55 PM
Here you are:-


<form name = "myform">
<input type = "text" name = "txt1" size = "4" maxlength = "4" onchange = "checkIt()"
</form>

<script type = "text/javascript">
function checkIt() {
var x = document.myform.txt1.value;
if (!/^([A-Z]{2}[0-9]{2})$/g.test(x)) {
alert ("Entry must be in the form AB34");
document.myform.txt1.value = ""; // clear the field
setTimeout("document.myform.txt1.focus()", 10); // refocus on it
return false;
}
else {alert ("Entry OK")} // for testing
}
</script>

This requires AB34 with the letters in upper case. If lower case is permissible, change to
if (!/^([A-Z]{2}[0-9]{2})$/gi.test(x)) {

Quizmaster: What is the Latin name of the province in Canada which means "New Scotland" in English?
Contestant: Johannesburg.

bill737
06-18-2010, 05:31 PM
This works great! Thank you so much!

If it's no trouble, can you please explain what exactly the following line of code does:

setTimeout("document.myform.txt1.focus()", 10);

Again, I can't thank you enough!

Philip M
06-18-2010, 05:57 PM
This works great! Thank you so much!

If it's no trouble, can you please explain what exactly the following line of code does:

setTimeout("document.myform.txt1.focus()", 10);

Again, I can't thank you enough!

Overcomes a bug in Firefox by creating a very small delay of 10ms before re-focusing on the field.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum