If you are new to kohanaframework, implementing validation will be an adventure, especially if you are looking for ajax validation. In this article I will present a simple way to implement somel necessary validations using ajax in a sign up form. Lets start from the view. To each field that need to be validated I have added the class 'validate'. Since the validation of 'Password confirmation' field is related to 'Password', I have given that as rel attribute of Password confirmation. If there is more than one related fields it can be given like “rel='field1|field2|field3' ”.All these setup is just to inform our javascript code, that these fields must be validated. Now lets take a look into our model, where we define our validation rules. The reason why we add rules and validation function in model is the easiness of calling them from different functions. The first function rules() will return the validation rules for all fields, which we can check against the required fields. This is pretty straight forward, but knowing this 'syntax' is the trickiest part. We can write custom validation functions too, as given for email field. There we are checking if the email already exists in db are not. Custom validation function will have two parameters, first one will be an object of validation and second will be the field. Our custom function will not return anything, instead we can add errors to the validation object. Since in PHP objects are passed by reference, it will work absolutely fine. The validate() function create a new object of validation class and will add rules for the given fields. The difference between validating form submission and ajax validation lies here. Here we will be adding rules for only the given field, instead of all fields in the form.Moving to the controller, we can see the action called by ajax. Controller_User is extending Controller_Default (not shown here) which extends Controller_Template. First we will disable auto rendering of view if requested using ajax. Then we are checking if the request is a post. By calling the validate function we are binding all the rules for that particular field. Next will check if the value satisfies all rules and if not, it will return the error message. Next we will see the javascript code that will do ajax validation and will show errors in the front end, if any. Here you can see how we are managing related fields. The validate function will be called on blur of each field with class 'validate'. The return value will be list of errors in json encoded format. We will parse this and will add the error message just after the field.In this article we have seen how to implement ajax validation in Kohana framework. We can use the above code with no or less modifications almost anywhere. My intention is to present the concept, in a simple way. Hope this makes sense and if you find better alternatives, feel free to add a comment.
References : Kohana Validation class