Skip to content Skip to sidebar Skip to footer

Validate A Booking Form With More Than One User Record

I need to validate my form using jQuery or JavaScript when the page is submitted. The conditions to validate my form are: Name, age, and email of first passenger is compulsory. I

Solution 1:

We can restate the four requirements as follows:

  • At least one name must be entered.

  • For each name that has been entered, the age and email address must be specified.

  • There must be a unique email address for each name.

  • The "terms and conditions" checkbox must be checked.

The snippet below validates all of these requirements. Note the following.

  • The HTML contains a single entry which is duplicated when the page loads. The global variable numEntries specifies the desired number of entries in the form.

  • We use entryCount to keep track of how many names have been entered into the form.

  • A hash is used to store the name corresponding to each email address. We look up each new email address in this hash to see if a name has already been assigned.

var numEntries = 10;

// Remove whitespace from beginning and end of string.functionstrip(s) {
  return s.replace(/^\s+|\s+$/, '');
}

window.onload = function () {
  // Make ten entries and store them in an array.var form = document.getElementById('entryForm'),
      entry = form.getElementsByTagName('div')[0],
      nextSibling = entry.nextSibling,
      entries = [entry];
  for (var i = 1; i < numEntries; ++i) {
    var newEntry = entry.cloneNode(true);
    form.insertBefore(newEntry, nextSibling);
    entries.push(newEntry);
    entry = newEntry;
  }
  // Make it easy to look up field values for each entry.
  entries.forEach(function (entry) {
    ['name', 'age', 'email', 'phone'].forEach(function (field) {
      entry[field] = entry.getElementsByClassName(field)[0];
    });
  });
  // Attach a validation function to the form submission button.document.getElementById('submitButton').onclick = function () {
    if (!document.getElementById('agreementBox').checked) {
      alert('Error: you must agree to our terms and conditions.');
      return;
    }
    var entryCount = 0,
        emailHash = {};
    for (var i = 0; i < numEntries; ++i) {
      var entry = entries[i],
          name = strip(entry.name.value);
      if (strip(entry.name.value) !== '') {
        var age = strip(entry.age.value),
            email = strip(entry.email.value);
        if (age === '' || email === '') {
          alert('Error: you must enter the age and email address of ' + name + '.');
          return;
        }
        if (emailHash[email] !== undefined) {
          alert('Error: ' + name + ' has the same email address as ' +
                emailHash[email] + '. Addresses must be unique.');
          return;
        }
        emailHash[email] = name;
        ++entryCount;
      }
    }
    if (entryCount == 0) {
      alert('Error: you must enter at least one name.');
      return;
    }
    alert('Success! The form has been validated.');
  };
};
.agreement {
  font-family: sans-serif;
  font-size: 12px;
}
  
<formid="entryForm"><div><inputclass="name"type="text"placeholder="Full Name" /><inputclass="age"type="number"placeholder="Age" /><select><optionvalue="Male">Male</option><optionvalue="Female">Female</option></select><inputclass="email"type="email"placeholder="E-mail" /><inputclass="phone"type="number"placeholder="Mobile" /></div><pclass="agreement"><inputid="agreementBox"type="checkbox"> Agree to our terms and conditions
  </p><inputid="submitButton"type="submit"value="submit" /></form>

Below is a version that uses exactly the HTML you posted in your question.

// Remove whitespace from beginning and end of string.functionstrip(s) {
  return s.replace(/^\s+|\s+$/, '');
}

window.onload = function () {
  // Find the entry input areas and store them in an array.var form = document.getElementsByTagName('form')[0];
  var entries = form.getElementsByTagName('div');
  for (var i = 0; i < entries.length; ++i) {
    var entry = entries[i],
        inputs = entry.getElementsByTagName('input');
    // Make it easy to look up field values for each entry.
    ['name', 'age', 'email', 'phone'].forEach(function (field, ix) {
      entry[field] = inputs[ix];
    });
  }
  // Attach a validation function to the form submission button.var inputs = form.getElementsByTagName('input'),
      agreementBox = inputs[inputs.length - 2],
      submitButton = inputs[inputs.length - 1];
  submitButton.onclick = function () {
    if (!agreementBox.checked) {
      alert('Error: you must agree to our terms and conditions.');
      return;
    }
    var entryCount = 0,
        emailHash = {};
    for (var i = 0; i < entries.length; ++i) {
      var entry = entries[i],
          name = strip(entry.name.value);
      if (strip(entry.name.value) !== '') {
        var age = strip(entry.age.value),
            email = strip(entry.email.value);
        if (age === '' || email === '') {
          alert('Error: you must enter the age and email address of ' + name + '.');
          return;
        }
        if (emailHash[email] !== undefined) {
          alert('Error: ' + name + ' has the same email address as ' +
                emailHash[email] + '. Addresses must be unique.');
          return;
        }
        emailHash[email] = name;
        ++entryCount;
      }
    }
    if (entryCount == 0) {
      alert('Error: you must enter at least one name.');
      return;
    }
    alert('Success! The form has been validated.');
  };
};
form {
  font-family: sans-serif;
  font-size: 12px;
}
<form><div><inputtype="text"id="fn1"placeholder="Full Name" /><inputtype="number"id="ag1"placeholder="Age" /><select><optionvalue="Male">Male</option><optionvalue="Female">Female</option></select><inputtype="email"id="em1"placeholder="E-mail" /><inputtype="number"placeholder="Mobile" /></div><div><inputtype="text"id="fn2"placeholder="Full Name" /><inputtype="number"id="ag2"placeholder="Age" /><select><optionvalue="Male">Male</option><optionvalue="Female">Female</option></select><inputtype="email"id="em2"placeholder="E-mail" /><inputtype="number"placeholder="Mobile" /></div><div><inputtype="text"id="fn3"placeholder="Full Name" /><inputtype="number"id="ag3"placeholder="Age" /><select><optionvalue="Male">Male</option><optionvalue="Female">Female</option></select><inputtype="email"id="em3"placeholder="E-mail" /><inputtype="number"placeholder="Mobile" /></div><div><inputtype="text"id="fn4"placeholder="Full Name" /><inputtype="number"id="ag4"placeholder="Age" /><select><optionvalue="Male">Male</option><optionvalue="Female">Female</option></select><inputtype="email"id="em4"placeholder="E-mail" /><inputtype="number"placeholder="Mobile" /></div><div><inputtype="text"id="fn5"placeholder="Full Name" /><inputtype="number"id="ag5"placeholder="Age" /><select><optionvalue="Male">Male</option><optionvalue="Female">Female</option></select><inputtype="email"id="em5"placeholder="E-mail" /><inputtype="number"placeholder="Mobile" /></div><div><inputtype="text"id="fn6"placeholder="Full Name" /><inputtype="number"id="ag6"placeholder="Age" /><select><optionvalue="Male">Male</option><optionvalue="Female">Female</option></select><inputtype="email"id="em6"placeholder="E-mail" /><inputtype="number"placeholder="Mobile" /></div><div><inputtype="text"id="fn7"placeholder="Full Name" /><inputtype="number"id="ag7"placeholder="Age" /><select><optionvalue="Male">Male</option><optionvalue="Female">Female</option></select><inputtype="email"id="em7"placeholder="E-mail" /><inputtype="number"placeholder="Mobile" /></div><div><inputtype="text"id="fn8"placeholder="Full Name" /><inputtype="number"id="ag8"placeholder="Age" /><select><optionvalue="Male">Male</option><optionvalue="Female">Female</option></select><inputtype="email"id="em8"placeholder="E-mail" /><inputtype="number"placeholder="Mobile" /></div><div><inputtype="text"id="fn9"placeholder="Full Name" /><inputtype="number"id="ag9"placeholder="Age" /><select><optionvalue="Male">Male</option><optionvalue="Female">Female</option></select><inputtype="email"id="em9"placeholder="E-mail" /><inputtype="number"placeholder="Mobile" /></div><div><inputtype="text"id="fn10"placeholder="Full Name" /><inputtype="number"id="ag10"placeholder="Age" /><select><optionvalue="Male">Male</option><optionvalue="Female">Female</option></select><inputtype="email"id="em10"placeholder="E-mail" /><inputtype="number"placeholder="Mobile" /></div><inputtype="checkbox"value="Agree to our terms and agreement" /><inputtype="submit"value="submit" /></form>

Post a Comment for "Validate A Booking Form With More Than One User Record"