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
    Regular Coder
    Join Date
    Mar 2010
    Location
    Orlando, FL
    Posts
    161
    Thanks
    4
    Thanked 8 Times in 8 Posts

    How do I test for alphanumeric expressions in input field

    I searched the forum for an answer to this question, but found nothing that was able to answer my question. I have a form and I need to validate a field against three rules:

    1) The field need to be between 6 and 12 characters
    2) It can only have letters, numbers, and the underscore
    3) It cannot contain a space or other special characters

    I want the validate to happen in real-time. I have the first rule working great. Here is the code for that:
    Code:
    var username = document.getElementById('registerUsername');
    if((username.value.length < 6) || (username.value.length > 12))
    			{
    			document.getElementById('usernameValidate').innerHTML="Incorrect.";
    			}else{
    			document.getElementById('usernameValidate').innerHTML="Correct.";
    			}
    How would I be able to incorporate checking for rules 2 and 3?
    Last edited by wojo1086; 09-12-2011 at 07:39 AM.

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,398
    Thanks
    12
    Thanked 570 Times in 563 Posts
    You can do all this with one single regex
    Code:
    var myRegex = /^[a-zA-Z0-9_]{6,12}$/;
    if(myRegex.test(document.getElementById('registerUsername'))) {
       // correct format here
    } else {
       // format is not correct
    }

  • #3
    Gütkodierer
    Join Date
    Apr 2009
    Posts
    2,127
    Thanks
    1
    Thanked 426 Times in 424 Posts
    Also notice how this

    Quote Originally Posted by devnull69 View Post
    Code:
    var myRegex = /^[a-zA-Z0-9_]{6,12}$/;
    is the exact same thing as this:

    Code:
    var myRegex = /^\w{6,12}$/;
    which makes the whole thing even easier.

  • Users who have thanked venegal for this post:

    devnull69 (09-12-2011)

  • #4
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,398
    Thanks
    12
    Thanked 570 Times in 563 Posts
    Woah ... I never noticed the underscore was already part of \w ... thanks


  •  

    Posting Permissions

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