Link to home
Create AccountLog in
Avatar of Robert Granlund
Robert GranlundFlag for United States of America

asked on

Javascript Form Validation

Is there a way to have javascript form validation that does not use a popup box, for each field missed that is required?  Is there a way to show a full stylized list of all required fields, once the submit is clicked?


function validateForm()
{
var street_address=document.forms["myForm"]["street_address"].value;
if (street_address==null || street_address=="")
  {
  alert("A street address must be filled out");
  return false;
  }

var city=document.forms["myForm"]["city"].value;
if (city==null || city=="")
  {
  alert("A city name must be filled out");
  return false;
  }
}

Open in new window

Avatar of Albert Van Halen
Albert Van Halen
Flag of Netherlands image

Put all errors into a string and display the string if not empty.

In the example all errors are put into an array and it is being alerted if it contains items.
function validateForm() {
  var errors = [];
  var street_address=document.forms["myForm"]["street_address"].value;
  if (street_address==null || street_address=="") {
    errors.push("A street address must be filled out");
  }

  var city=document.forms["myForm"]["city"].value;
  if (city==null || city=="") {
    errors.push("A city name must be filled out");
  }

  if(errors.length > 0) {
    alert(errors.join("\n"));
    return false;
  }
}

Open in new window

Avatar of onlyaymie
onlyaymie

You might be interested in OpenVL  http://openvl.info/
Avatar of Robert Granlund

ASKER

@AlbertVanHalen:

Thank you for your response.  Is there a way to get the javascript to print on the actual page instead of in an alert box?  Can it be styled?
ASKER CERTIFIED SOLUTION
Avatar of Albert Van Halen
Albert Van Halen
Flag of Netherlands image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer