Ask the Expert

Code for validation on a field

I would like to ask you if you have JavaScript code which does the validation on a field. If nothing is put in to the field from the user, a warning pops up and reminds the user that the field has to be filled in or something. I would appreciate it if you can help me on this.
The following code contains HTML and JavaScript that implements one simple way of doing this. You should be able to save the following code as an HTML file in your file system to test it. You could put the JavaScript functions in the JSHeader event of your form and add the call to ValidateForm in the form's onSubmit event.

 &lthtml> &lthead> &lttitle&gtSearchDomino Test</title> &ltSCRIPT language="JavaScript"> function validateForm(form){ // Last mods 020518 - dhatter@libertastechnologies.com - www.libertastechnologies.com with(form){ if(! isFieldEmpty(email)){ return(false); } return(true); } } function isFieldEmpty(objField){ // Last mods 020518 - dhatter@libertastechnologies.com - www.libertastechnologies.com if(objField.value==''){ alert('Please enter a value for ' + objField.name + '.'); objField.focus(); return(false); }else{ return(true); } } </SCRIPT> </head> &ltbody> &ltFORM action="" method="POST" onSubmit="return(validateForm(document.forms[0]))"> e-Mail Address: &ltINPUT name="email" value="" type="text">&ltBR> &ltINPUT type="submit" value="Submit"> </FORM> </body> </html>


This was first published in May 2002

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: