0

currently I have an Html form with javascript validation. Currently the errors are showing in a popup by using the alert command.... how I can display error messages next to the text boxes please? Below is my current code:

 if (document.gfiDownloadForm.txtFirstName.value == '') {
  alert('Please fill in all required fields');
  return false;
 }

 var filter = /^([a-zA-Z '-]+)$/i
 if (filter.test(document.gfiDownloadForm.txtFirstName.value) == false) {
  alert('Please enter a valid First name');
  return false;
 }

 var filter = /^([a-zA-Z '-]+)$/i
 if (filter.test(document.gfiDownloadForm.txtLastName.value) == false) {
  alert('Please enter a valid Last name');
  return false;
 }


 if (document.gfiDownloadForm.txtCompany.value == '') {
  alert('Please enter a Company name');
  return false;
 }
1
  • 1
    Make sure to also have server side validation ;) Commented Jan 12, 2011 at 11:33

2 Answers 2

3

You'll need to add additional form elements (likely a span since they're inline, rather than a div which is a block element) to hold the error messages next to your input form elements and give it an id so that you can reference it in your javascript. Something like this:

<input type="text" id="txtFirstName" /><span id="firstNameError"></span>

Then in your Javascript code you'd set the innerHTML of that form element to your error message if it doesn't validate, or to an empty string '' if it does validate, like so:

if (filter.test(document.gfiDownloadForm.txtFirstName.value) == false) {
    document.getElementById("firstNameError").innerHTML = 'Please enter a valid First name.';
    return false;
}
else {
    document.getElementById("firstNameError").innerHTML = '';
    return true;
}
Sign up to request clarification or add additional context in comments.

2 Comments

You're returning false in both cases; mistake? Moreover, when using DOM level 2 event binding, you should use the corresponding functions/properties of the Event interface to stop default behaviour.
Yes, that's a mistake on my part. Since the return value didn't seem to be used in the sample code in the question, I didn't pay too much attention to it when copying it over to my own. Edited the answer to return true if it validates correctly.
1

You should have a <div> or <span> next to the input field, and instead of an alert statement simply set the content of the <div> to the appropriate error message.

e.g.

if (document.gfiDownloadForm.txtCompany.value == '') {
  document.getElementById('company_error').innerHTML = 'Please enter a company name';
  return false;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.