If you’re a web programmer, then you are probably familiar with using JavaScript to add functionality to a web page. JavaScript can be used to do a lot of different things, one of which is validating user input on forms, etc.
The HTML standard, by itself, does not support any kind of validation for form fields, so you have to use scripting languages like JavaScript or full-fledged programming languages like ASP.NET.
The easiest way to validate user input is to use JavaScript since most modern browsers support it and it’s very easy to implement. Using client-side JavaScript also reduces the load on servers since the processing is being done locally on the clients computer.
A very simple client side JavaScript function would look something like this:
function validateForm(form)
{
var isvalid = true;
if(form.inputfield_email.value == "")
isvalid = false;
if(form.inputfield_dateofbirth.value == "")
isvalid = false;
if(form.inputfield_address.value == "")
isvalid = false;
return isvalid;
}
This function basically takes a form object as a parameter and returns either True or False. The function checks the inputs of three form fields named inputfield_email, etc to make sure they are not left blank.
You can easily call this function from your form by using the onsubmit method:
<form method="POST" action="ProcessData.php" onsubmit="return validateForm(this)
The action property for the form is set to ProcessData.php, which will only load if the value returned from onsubmit is True and not False.
Pretty simple eh? Of course, this is a very basic example, but you get the idea. You can use regular expressions to make sure the email address is properly formatted and that phone numbers are the proper length, etc, etc.
If you want to display some feedback to the users if there is an error detected, you can add to the previous code:
function validateForm(form)
{
var errors = [];
if(form.inputfield_email.value == "") {
errors.push("Please enter a valid email address.");
}
if(form.inputfield_dateofbirth.value == "")
errors.push("Please enter a date of birth.");
}
if(form.inputfield_address.value == "")
errors.push("Please enter an address.");
}
if(errors.length > 0) {
alert("There was a problem while validating your request: \n- " + errors.join("\n- "));
return false;
}
return true;
}
That’s it! The fields will be checked and it any of them are left blank, a message will pop up saying there was a problem with the request along with the appropriate statement.
If you have any issues with client side validation using JavaScript, post a question here and I’ll try to help. Enjoy!







Be The First To Comment
Please Leave Your Comments Below