SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    May 2003
    Location
    Creve Coeur, Il.
    Posts
    17
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Validation looping question

    I have a form with 20 text fields. I am wanting to loop through them and validate the characters. I can write 20 routines, one for each, but I'd like to loop through them. More efficient imho.

    The following sample works for the first field. But I am trying to find out how do I reference theForm.Student1 to use the "a" variable? I have tried theForm.Student + a.value and some variations, but it bombs.

    I am sure it is simple. Any thoughts?

    for (a=1; a<20; a++)
    {
    if (theForm.Student1.value.length > 0)
    {
    var checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var checkStr = theForm.Student1.value;
    var allValid = true;
    for (i = 0; i < checkStr.length; i++)
    {
    ch = checkStr.charAt(i);
    for (j = 0; j < checkOK.length; j++)
    if (ch == checkOK.charAt(j))
    break;
    if (j == checkOK.length)
    {
    allValid = false;
    break;
    }
    }
    }
    }

  2. #2
    SitePoint Enthusiast
    Join Date
    Dec 2007
    Posts
    66
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Forms have an 'elements' array of the input elements (button, checkbox, hidden, password, radio, reset, select, submit, text, or textarea) in the form. So:

    Code:
    for (i = 1; i < theForm.elements.length; i++) {
        el = theForm.elements[i];
        // Do whatever you want
        // You might want to perform some tests to ensure you are not looking
        // at a button, etc.:
        switch (el.tagName) {
            case 'INPUT':
                if (el.type == 'text') {
                    // validate...
                }
                break;
            case 'TEXTAREA':
                // validate...
                break;
        }
    }

  3. #3
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,714
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    Code Javascript:
    for (a=1; a<20; a++)
    {
    if (theForm['Student'+a].value.length > 0)
    {
    ...

    You may wish to use a pre-packaged form validation script for which most of the work has already been done for you.


Bookmarks

Posting Permissions

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