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 11 of 11
  1. #1
    Regular Coder tpeck's Avatar
    Join Date
    Oct 2002
    Location
    Sydney, Australia
    Posts
    884
    Thanks
    53
    Thanked 6 Times in 5 Posts

    validate a form field for numbers only

    Hi, I need a simple way to validate a form field.

    The form only has this one field and it MUST only accept digits - actually only the digits 1 to 1001 inclusive - no spaces - no anything else.

    I tried to adapt this validator code - you can see my pathetic effort in blue.

    If it worked, I could junk the stuff I don't need, but alas, it doesn't.

    What can I do?

    Code:
        // Validator Object
        var valid = new Object();
    
        // REGEX Elements
    
            // matches zip codes
            valid.zipCode = /\d{5}(-\d{4})?/;
            
            // matches number
            valid.number = /^\d*/;
    
            // matches $17.23 or $14,281,545.45 or ...
            valid.Currency = /\$\d{1,3}(,\d{3})*\.\d{2}/;
    
            // matches 5:04 or 12:34 but not 75:83
            valid.Time = /^([1-9]|1[0-2]):[0-5]\d$/;
    
            //matches email
            valid.emailAddress = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;
    
            // matches phone ###-###-####
            valid.phoneNumber = /^\(?\d{3}\)?\s|-\d{3}-\d{4}$/;
    
            // International Phone Number
            valid.phoneNumberInternational = /^\d(\d|-){7,20}/;
    
            // IP Address
            valid.ipAddress = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
    
            // Date xx/xx/xxxx
            valid.Date = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;
    
            // State Abbreviation
            valid.State = /^(AK|AL|AR|AZ|CA|CO|CT|DC|DE|FL|GA|HI|IA|ID|IL|IN|KS|KY|LA|MA|MD|ME|MI|MN|MO|MS|MT|NB|NC|ND|NH|NJ|NM|NV|NY|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VA|VT|WA|WI|WV|WY)$/i;
    
            // Social Security Number
            valid.SSN = /^\d{3}\-\d{2}\-\d{4}$/;
    
        
        function validateForm(theForm) {
    
            var elArr = theForm.elements; 
    
            for(var i = 0; i < elArr.length; i++) {
    
               with(elArr[i]) { 
    
                  var v = elArr[i].validator; 
    
                  if(!v) continue; 
    
                  var thePat = valid[v]; 
    
                  var gotIt = thePat.exec(value); 
    
                  if(! gotIt){
                     alert(name + "Failure to match " + v + " to " + value);                  
                     elArr[i].select();
                     elArr[i].focus(); 
                     return false;
                  }
               }
            }
    
            return true;
    
        }
    The actual form is:

    Code:
    <form id="goto" onsubmit="return validateForm(goto);return gopage()">
    <input id="exField" validator="number" type="text" size="3" maxlength="4">
    <input type="submit" name="go" value="go"></form>
    The difference between genius and stupidity is that genius has its limits. (Albert Einstein)

  • #2
    Senior Coder nikkiH's Avatar
    Join Date
    Jun 2005
    Location
    Near Chicago, IL, USA
    Posts
    1,973
    Thanks
    1
    Thanked 32 Times in 31 Posts
    "only the digits 1 to 1001 inclusive"

    If it's that specific, I'd not even try regular expressions. I'd just parseInt and check the value instead of this big script to check one value.
    Also, 'this' is a cool keyword.
    And I don't know if you can use 2 returns like that.

    Code:
    <form id="goto" onsubmit="return validateForm(this);">
    <input id="exField" validator="number" type="text" size="3" maxlength="4">
    <input type="submit" name="go" value="go"></form>
    Code:
    function validateForm(theForm) {
       theValue = parseInt(theForm.exField.value);
       return (! isNaN(theValue) && theValue >= 1 && theValue <= 1001);         
    }

    If this post contains any code, I may or may not have tested it. It's probably just example code, so no getting knickers in a bunch over a typo, OK? If it doesn't have basic error checking in it, such as object detection or checking if objects are null before using them, put that in there. I'm giving examples, not typing up your whole app for you. You run code at your own risk.
    Bored? Visit
    http://www.kaelisspace.com/

  • #3
    Regular Coder tpeck's Avatar
    Join Date
    Oct 2002
    Location
    Sydney, Australia
    Posts
    884
    Thanks
    53
    Thanked 6 Times in 5 Posts
    OK thanks. I'll use your function. And you're right: that double return falls over.

    So I have tried to incorporate your function into the "gopage" function:

    Here is the form then:

    Code:
    <form id="goto" onsubmit="return gopage(this);">
    <input id="exField" type="text" size="3" maxlength="4">
    <input type="submit" name="go" value="go"></form>
    The go page function below looks a little complex, but all it is doing is calling other functions to create a particular path and html value given the form input. It then shoots off to that page and works beautifully (thanks to others who have helped).

    But now I would like to incorporate your "validateForm" function. Where exactly should I place it? I just tried the blue position and it failed, but I think it's because of the lack of a return somewhere. Am I right?

    Code:
    function validateForm(theForm) {
       theValue = parseInt(theForm.exField.value);
       return (! isNaN(theValue) && theValue >= 1 && theValue <= 1001);         
    }
    
    /* pads with leading 0s, e.g. numberPad(51,4) = 0051  */
    function numberPad(number,finalWidth) {
      var zeros = '';
      var addWidth;
      var initWidth;
      initWidth = ('' + number).length;
      addWidth = finalWidth - initWidth;
      if(addWidth) {
        for(var i=1; i<=addWidth; i++) {
          zeros = '0' + zeros;
        }
      }
      return zeros + number;
    }
    
    /* get lesson from exercise number */
    function getLesson(ex) {
      return Math.floor((ex-1)/40 + 1);
    }
    
    /* get block from lesson */
    function getBlock(lesson) {
      return Math.floor((lesson-1)/5) + 1;
    }
    
    /* get path from exercise */
    function getPath(ex) {
      var part1;
      var part2;
      var part3;
      var part4;
      lesson = getLesson(ex);
      block = getBlock(lesson);
      startLesson = 5 * block - 4;
      endLesson = 5 * block;
      part1 = 'L' + numberPad(startLesson, 2) + '-' + numberPad(endLesson, 2);
      part2 = 'L' + numberPad(lesson, 2);
      part3 = numberPad(ex, 3);
      part4 = numberPad(ex, 3) + '.html';
      path = '../../../'+ part1 + '/' + part2 + '/' + part3 + '/' + part4;
      if (part1=='L26-30') {
      path= '../../../L21-25/L25/1001/1001.html';
      }
      return path;
    }
    
    function gopage() {
      var ex = document.getElementById('exField').value;
      top.location = getPath(ex);
      validateForm(theForm);
      return false;
    }
    // -->
    Last edited by tpeck; 02-13-2007 at 03:24 PM.
    The difference between genius and stupidity is that genius has its limits. (Albert Einstein)

  • #4
    Senior Coder nikkiH's Avatar
    Join Date
    Jun 2005
    Location
    Near Chicago, IL, USA
    Posts
    1,973
    Thanks
    1
    Thanked 32 Times in 31 Posts
    Try this.

    <form id="goto" onsubmit="if (validateForm(this)) {return gopage();} else {return false;}">

    If this post contains any code, I may or may not have tested it. It's probably just example code, so no getting knickers in a bunch over a typo, OK? If it doesn't have basic error checking in it, such as object detection or checking if objects are null before using them, put that in there. I'm giving examples, not typing up your whole app for you. You run code at your own risk.
    Bored? Visit
    http://www.kaelisspace.com/

  • #5
    Regular Coder tpeck's Avatar
    Join Date
    Oct 2002
    Location
    Sydney, Australia
    Posts
    884
    Thanks
    53
    Thanked 6 Times in 5 Posts
    Yes, thanks very much. I tried that and it looks like it should work, but it only allows a correct response (i.e. 1, 2, 3, etc., to 1001).

    But if I enter a combination of letters for instance, say, "zzz", I get an error -

    ...\1a.lessons\LNaN-NaN\LNaN\zzz\zzz.html

    So the validation is intercepting but not sending back to try again.

    Do you know what I can do about this?

    Should I set up a demo?

    Thanks for your help.
    The difference between genius and stupidity is that genius has its limits. (Albert Einstein)

  • #6
    Senior Coder nikkiH's Avatar
    Join Date
    Jun 2005
    Location
    Near Chicago, IL, USA
    Posts
    1,973
    Thanks
    1
    Thanked 32 Times in 31 Posts
    What is your goal here? Normally validation is supposed to fail if something is wrong. Did you want some other behavior that has to do with that go page function?
    If so, please post the code for that one and we'll incorporate the validation into it instead of making it separate.

    If this post contains any code, I may or may not have tested it. It's probably just example code, so no getting knickers in a bunch over a typo, OK? If it doesn't have basic error checking in it, such as object detection or checking if objects are null before using them, put that in there. I'm giving examples, not typing up your whole app for you. You run code at your own risk.
    Bored? Visit
    http://www.kaelisspace.com/

  • #7
    Regular Coder tpeck's Avatar
    Join Date
    Oct 2002
    Location
    Sydney, Australia
    Posts
    884
    Thanks
    53
    Thanked 6 Times in 5 Posts
    I am trying to prevent the user from getting a 404 page error if he or she enters anything but 1 through to 1001.

    Trouble is, it shoots the user off to a page called "zzz.html" if the user enters "zzz" etc.

    It works with numbers, though. So I need a validation routine - yours I am sure is good - to prevent the user going anywhere if there is a bad input.

    Here is a demo that should demonstrate what is happening:

    http://aapress.com.au/demo/backforwa...1/001/001.html

    I've just set it up only for pages 001.html and 002.html (the first two coloured numbers on the bar).

    If you enter 2 and press go, you get taken to page 002.html, and vice-versa.

    But notice what happens if you enter, say, "zzz"...

    ...it goes looking for a page called:

    http://aapress.com.au/demo/backforwa...N/zzz/zzz.html

    That's the problem.

    Now I have your routine, but I don't know how or where to apply it.

    Does anyone have any thoughts? It has to perhaps alert the user not to use letters. I can make an alert, but how to get it to come up. Better still would be if nothing happened at all if the user enters a dud input.
    The difference between genius and stupidity is that genius has its limits. (Albert Einstein)

  • #8
    Banned
    Join Date
    Jan 2007
    Posts
    10
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Dont be a fat purple ape!

  • #9
    Regular Coder tpeck's Avatar
    Join Date
    Oct 2002
    Location
    Sydney, Australia
    Posts
    884
    Thanks
    53
    Thanked 6 Times in 5 Posts
    Do you have anything relevant to say?
    The difference between genius and stupidity is that genius has its limits. (Albert Einstein)

  • #10
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,300
    Thanks
    203
    Thanked 2,561 Times in 2,539 Posts
    function validateForm(theForm) {
    theValue = parseInt(theForm.exField.value);
    if (isNaN(theValue)) {return false;}
    if (theValue <1 || theValue >1001) {return false;}
    return gopage(theValue);
    }

  • #11
    Regular Coder tpeck's Avatar
    Join Date
    Oct 2002
    Location
    Sydney, Australia
    Posts
    884
    Thanks
    53
    Thanked 6 Times in 5 Posts
    So simple when you see it - simple for a non-ape I guess...(what's wrong with that guy?)

    Thanks so much to both of you - it works - as you can see...

    http://aapress.com.au/demo/backforwa...1/001/001.html

    Cheers!
    The difference between genius and stupidity is that genius has its limits. (Albert Einstein)


  •  

    Posting Permissions

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