JavaScript validation can be quite tricky if you have never done it before, but this tutorial should make it easier. So what can you validate? You can use JavaScript as a presence check and a type check as well as checking for reasonable dates and email addresses. Please note that I used the word reasonable, rather than correct as the user can still enter an incorrect date or email address even if it is in the right format!
The Presence Check This check is used when you've got a form on your site and you want to make sure certain fields are filled in before it is submitted. The basic JavaScript required for this is:
|
function validate_presence(field,errormessage)
{ with (field) { if (value==null||value=="") {alert(errormessage);return false} else {return true} } } |
This code basically tells your browser to check a certain field when the form is submitted. If it is empty, then it will show an error message. If not, then it will let the browser submit the form. The above code can be used for all the fields in your form, as you simply add the JavaScript for each field. For example:
|
function validate_presence(field,errormessage)
{ with (field) { if (value==null||value=="") {alert(errormessage);return false} else {return true} } } function validate_form(thisform) { with (thisform) { if (validate_presence(name,"You must enter your name!")==false) {name.focus();return false} if (validate_presence(email,"You must enter your email address!")==false) {email.focus();return false} } } |
And how do you link your form to this JavaScript? You simply add the following code to your <form> tag:
| onSubmit="return validate_form(this)" |
I will write some more tutorials on JavaScript validation soon.








