DelphiFAQ Home Search:
General :: Web publishing :: JavaScript
Code snippets to add functionality to your HTML pages, preferably cross-browser.

Articles:

This list is sorted by recent document popularity (not total page views).
New documents will first appear at the bottom.

Featured Article

Validating user input in a form

Question:

How can I validate a form's user input?

Answer:

You can either put an onblur event handler on each input field (text input, radio buttons, check boxes, select lists) which will get triggered each time a user leaves any field. This is useful if there are many input fields on the screen that can be evaluated independently.

If you either have only a few fields or if some of the fields' rules depend on other fields, then you might prefer to validate upon submission of the form.
Use the form's onsubmit event for that as the following example shows.

If the validation fails (user puts in an age under 18) then the data does not get posted and the form stays.

<html><body>
 
 <script language="JavaScript">
 <!--
 function valid(form) {
 var field = form.age;  
 var userAge = parseInt(field.value);   
 
 	if (!userAge) {
 		alert("You must indicate your age.");
 		return false;
 	} 
 	else if (userAge >= 18) {  
 		alert("Thank you, you can proceed to our special content.");  
 		return true;
 	} 
 	else {
 		alert("You are only " + userAge + ". Try again when you are 18."); 
 		field.focus();
 		field.select();
 		return false;
 	}
 }
 // -->
</script>
 
 
 <form method="GET" action="http://www.coders-corner.com/" onSubmit="return valid(this)">
 Your age: <input type="text" name="age" size="2"><BR>
 <input type="submit" value="Tell Age">
 </form>
 
 </body></html>
 

Generated 0:02:07 on Nov 24, 2017