Validation with onBlur event using PHP AjaxWe have seen how to validate form using PHP & Ajax. We will improve the script further to have error message displayed by the side of the form component as we move out of the particular html form member. For example as we type the first name and move to the next member our validation will check and display the error message if any. This will give better user experience as the user comes to know immediately what the error is.
Demo form validation
Checking the availability of userid
Here we can check the availability of userid and immediately tell the user about the status. We need not send all the data to server and check the availability of userid. This way while the user is entering the other field data we can display the result of availability of userid to the user. To keep the script simple we have not used database table here and only checked against some selected userids. So if the userid is abcd or efgh then the userid validation will fail and for any other value it will pass.
Using the div tag to display the status
Each component of the form will have its own div tag to display the error message by the side of it. Each one is named related to the input box for easy identification. Here is one example.
<tr><td>userid</td><td> <input type=text name=userid id='userid' onBlur=ajaxFunction('userid_div')></td><td><div id="userid_div"></div></td></tr>
onBlur event handler
We have used the same techniques of form data collection and posting to server as we discussed in Ajax From Validation part 1. So we are not explaining again.
The server side script
Here we have collected all the data first and then used one switch statement to validate and display message for particular form component and post back the error message.
Finally the form is submitted.
Now if the form is submitted then all the data will be posted to server side for further processing. We left this part as you can develop this to integrate to your requirment
There are different ways to handle such script, you can try on your own to further improve or modify the script.
Download the form validation code here