www.webdeveloper.com
Results 1 to 3 of 3

Thread: Regexp to limit number of input characters in a form

  1. #1
    Join Date
    Dec 2004
    Posts
    47

    Regexp to limit number of input characters in a form

    I am trying to limit the input for a particular field to 3 digit numeric exactly. I am using a regular expression as follows:

    if (!/\d{3}/.test(theForm.code.value)) {
    alert("Field should have 3 digits only.");
    theForm.code.focus();
    return false;
    }

    I have also tried 3,3 instead of 3 and it seems like either should work but while it forces at least 3 digits it also allows 4 or more and I don't want that. Must be 3 exactly.

    Can anyone help me please - regular expressions are not one of my strong points!!!!

    Paul

  2. #2
    Join Date
    Dec 2004
    Posts
    47
    Found a fix - here it is for those that wan to know:

    if (!/^\d{3}$/.test(theForm.code.value)) {
    alert("Field should have 3 digits only.");
    theForm.code.focus();
    return false;
    }

    Need the ^ and $ to anchor the string to the exact number - no more no less!!

  3. #3
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,204
    The HTML tag property of maxlength="3" in the <input> tag would limit the maximum number of characters and then you would only need test if they were numeric.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles