DelphiFAQ Home Search:

Validating user input in a form


commentsThis article has not been rated yet. After reading, feel free to leave comments and rate it.


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">


Content-type: text/html


2008-02-21, 09:57:07
2015-02-01, 04:04:28
anonymous from Venezuela  
Kudos! What a neat way of thikinng about it.



NEW: Optional: Register   Login
Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option, or post under a registered account.

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity.
The owner of this web site reserves the right to delete such material.

photo Add a picture: