I'm working on a PHP application. It consists among others in html forms.
My question is how to implement form validation in an easy way and without requiring to duplicate validation code both on server (using PHP) and on browser (using Javascript).
I've devised a method using ajax. When an input looses focus (onblur event) it would make an ajax call to the server with the data it contains. The response would be an error message if the value is not valid or else an empty string.
But the code is very bloated on both server and browser and probably very buggy.
Could you point me in the right direction? Is always input validation that complex or I should be using a different approach?
Many thanks for those who take the time to read my post, and extra tanks to those who answer.
-
Its always good to validate on both browser and server...Drewdin– Drewdin2012-06-04 12:35:55 +00:00Commented Jun 4, 2012 at 12:35
-
client side is for user satisfaction and to limit the vulnerabilities from incoming data while server validation is for minimizing the security risks with data handling.swapnesh– swapnesh2012-06-04 12:37:24 +00:00Commented Jun 4, 2012 at 12:37
6 Answers
You always need server-side validation. However, you can make your life easier on the client side by relying on third-party libraries.
The easiest way to do basic validation is to use HTML5. This includes stuff like required field, number ranges and regex checks. No third party library required and browsers not capable of HTML5 will just ignore the validation. Which is no problem because the input will be validated on the server.
Another way would be to use the jQuery validation extension. With this library you only have to output some classes in your form fields.
If your are using the Zend_Form library to generate your forms and do the validation, you may have look at this article: http://codeutopia.net/blog/2008/04/04/client-side-validation-with-zend_form/
Comments
Input validation is very complex. You need to make sure the input is EXACTLY valid for your datatypes. This will usually include custom validation for every project. There is no substiute for both client side and server side validation.
Client side validation provides a snappy ui. Every thing that a user types in can be and should be validated client side so that no request has to be made to the server (reducing latency). This does not mean it is a substitue for server side validation, Because any person can see the request being made through a tool like firebug and submit any data they want to your server.
Server side you have to make sure data is of the type expected or you can open yourself up to sql injection or many other malicious attacks.
This is actually a very good reason to look at any of of the many php mvc frameworks. Most include form helpers that will significantly reduce the code you have to write for validation.
Comments
I strong recommend you Bassistance jQuery Validation plugin.
Always implement strong server side validation along with this.
Comments
I just post the data to a php that verifies everything via ajax. Then I return errors in a json string, each error has the name of the input that failed and an error string. Using jQuery I loop through the json object, and turn the inputs read and list error string. You can have the form submit to this script so that if javascript is turned off the form gets checked the the same php script.
function submitForm() {
$.ajax({
type: 'post',
url: 'cgi-bin/s_contact.php',
data: $("#contact").serialize(),
dataType: 'json',
success: function(data) {
if(data.answer == 'true') {
$("#showErrors").removeClass("progressbar");
$("#showErrors").html('<h2>Message Has Been Sent!</h2>');
setTimeout(function() {
window.location = $("#zsite").val();
},2000);
}
else {
se = $("#showErrors");
se.removeClass("progressbar");
se.html('');
se.append('<ul id="showeror"></ul>');
$.each(data,function(index,val) {
$('input[name='+index+']').css('background-color','#ff9');
$('#showeror').append('<li>'+val+'</li>');
});
}
},
error: function(msg) {
alert('Error: '+msg.error);
}
});
}
Comments
If you use a good javascript validation plugin you'll find they are quite portable with your server side validation. I probably need to explain this further so bear with me a little. I'll refer to http://rickharrison.github.com/validate.js/ to help me here, but there quite a few others.
Personally, I use the Symfony form framework for validation but you can use other frameworks or have a go at your own. The important thing is that you only define a set of validation rules once which can in-turn be used to drive the client-side validation.
This way you won't have any inconsistencies between the two separate validation processes, ensuring your application is DRY. Also, your the client-side validation can be loaded with the page since these rules have been pre-defined in your server-side code and you won't need all those ajax requests.
If you're not familiar with any PHP form frameworks or what I mean by defining your validation rules I can make things a bit clearer.
The below array could be used to loop over two $_POST fields, email and number, on the server-side. This information can also be easily passed to a client-side validator (e.g. json_encode($validators)). You might need to rework things a little, depending on what format the client-side expects its rules. But more importantly your validation logic is stored in one place.
$validators = array(
'email' => array(
'rules' => array(
'blank' => false,
'invalid' => '/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i',
),
'messages' => array(
'blank' => 'Missing email',
'invalid' => 'Invalid email',
),
),
'number' => array(
'rules' => array(
'blank' => false,
'invalid' => '/\d/',
),
'messages' => array(
'blank' => 'Missing number',
'invalid' => 'Not a number'
),
......