SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Zealot rhlowe's Avatar
    Join Date
    Sep 2006
    Location
    San Diego
    Posts
    116
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Dynamic form validation

    I have a problem, but that is besides the point. I an trying to update a validation script to account for dynamic form fields, where the field names go something like this:

    person1_firstNameMedia,
    person2_firstNameMedia,
    person3_firstNameMedia,
    etc.

    I didn't build the form nor can I change the form field names...

    Currently, validation for the fields looks like this:

    Code:
    if (theForm.person1_firstNameMedia.value=="") {
    	alert('Please enter first name for Person 1.');
    	theForm.person1_firstNameMedia.focus();
    	return false;
    }
    That works great if there is only one person to validate for, but what if there is 3? I am trying recursion, but cannot figure one thing out, and that is the point of this whole post,

    Can I dynamically generate the name of the field being validated?

    Something like this:

    Code:
    for (p = 1; p <= maxPeople; p++) {
    	if ('theForm.person' + p + '_firstNameMedia.value==""') {
    		alert('Please enter first name for Person' + p + '.');
    		'theForm.person' + p + '_firstNameMedia.focus();
    		return false;
    	}
    }
    I'd like the
    Code:
    if ('theForm.person' + p + '_firstNameMedia.value==""')
    to evaluate to
    Code:
    if (theForm.person1_firstNameMedia.value==""')
    or whichever person is in question, so that if properly tests the value of the form field.

    Can anyone help me see the error of my ways?
    San Diego Freelance Web Development Contractor
    Great Taste, no Filler. Now with no Trans Fat!

  2. #2
    Not yet perfect mattalexx's Avatar
    Join Date
    Oct 2005
    Location
    Taos, NM, US
    Posts
    441
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I don't know about dynamic form field names (unless you use eval()), but if the fields have id's, you could always do something like this:
    Code:
    for (p = 1; p <= maxPeople; p++) {
       elem = document.getElementById('person'+p+'_firstNameMedia');
       if (elem.value == "") {
          alert('Please enter first name for Person'+p+'.');
          elem.focus();
          return false;
       }
    }
    Matt Alexander
    Alexander Site Design

  3. #3
    SitePoint Zealot rhlowe's Avatar
    Join Date
    Sep 2006
    Location
    San Diego
    Posts
    116
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Duh me

    That option hadn't even crossed my mind, it worked perfectly, thanks!
    San Diego Freelance Web Development Contractor
    Great Taste, no Filler. Now with no Trans Fat!


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
  •