Tuesday, October 6, 2009

JavaScript : Form Validation 1

Calling a Javascript validation function

Instead of returning a constant true or false, we can instead call a function to figure out which return value to issue. This function can then be used to validate the form data, and decide whether to let the form submission continue, or to stop it in its tracks.

<form action="http://www.google.com/search" onsubmit="return validate(this);">
<label for="q">Search:</label>
<input type="text" name="q" id="q">
</form>

This function, validate(f), takes one parameter - a reference to the form. I prefer to use the Javascript keyword this.


Anatomy of a Javascript validation function

Onto the validation function. We need to do the following:

º Get a reference to the text field
º Check that it isn't empty
º If it is empty, stop the form submission
º otherwise let the form submission continue

In an external Javascript file, called validate.js:

function validate(f)  {
  if  (f.q.value=="")  {
  return false;
  }
  return true;
}

The parameter f is a reference to the current form (we passed in the Javascript reference this). Each field in a form can be referenced by f.fieldName. In our case, our field is called q. So f.q is a reference to our text field. Next we need to get a reference to the value of the text field, so we reference f.q.value.

By comparing f.q.value with an empty string we can test whether the text field is empty. If the field is indeed empty, then we want to stop the form submission. This is done by the statement return false.

At no stage do we need to submit the form using Javascript. The only thing the validation routine needs to do is decide whether to continue with the current form submission, or stop it in its tracks.

Taken From : http://www.isolani.co.uk/articles/simpleJavascriptAndForms.html

No comments:

Post a Comment