Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New to the CF scene
    Join Date
    Jun 2010
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Strict JavaScript Validation for Beginner

    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!

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,313
    Thanks
    203
    Thanked 2,563 Times in 2,541 Posts
    Here you are:-

    Code:
    <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.
    Last edited by Philip M; 06-18-2010 at 05:58 PM.

  • #3
    New to the CF scene
    Join Date
    Jun 2010
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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!

  • #4
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,313
    Thanks
    203
    Thanked 2,563 Times in 2,541 Posts
    Quote Originally Posted by bill737 View Post
    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.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •