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


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


How can I validate a form's user input?


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.

 <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."); 
 		return false;
 // -->
 <form method="GET" action="" onSubmit="return valid(this)">
 Your age: <input type="text" name="age" size="2"><BR>
 <input type="submit" value="Tell Age">

Generated 16:01:59 on Jun 23, 2017