Web Analytics Made Easy -
StatCounter How do I test for alphanumeric expressions in input field - CodingForum

Announcement

Collapse
No announcement yet.

How do I test for alphanumeric expressions in input field

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new 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; Sep 12, 2011, 01:39 AM.

  • #2
    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
    }

    Comment


    • #3
      Also notice how this

      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.
      .My new Javascript tutorial site: http://reallifejs.com/
      .Latest article: Calculators — Tiny jQuery calculator, Full-fledged OOP calculator, Big number calculator
      .Latest quick-bit: Including jQuery — Environment-aware minification and CDNs with local fallback

      Comment


      • #4
        Woah ... I never noticed the underscore was already part of \w ... thanks

        Comment

        Working...
        X
        😀
        🥰
        🤢
        😎
        😡
        👍
        👎