The problem of data validation has often been raised on Habré. Discussed server validation and validation on the client side. The use of various frameworks such as Yii, CodeIgniter, Vanadium, .NET, and jQuery plug-ins has been described for this purpose.
But there was no comprehensive look at these problems, as a logical single task for both the server and the client.
Validation of data should be transparent, regardless of where it goes - on the client or on the server, you do not need to break it into two separate parts and do a separate implementation for each of the tasks. After several projects and doing the same work, it comes to understanding that it would be good to combine these parts together and not waste your precious time on the actual duplication of code.
So, the question is posed as the creation of a transparent data validation system without logical separation between the client and server. Validation on the server side should automatically provide validation on the client side without additional efforts on the part of the programmer.
To solve this problem, we will use the already existing data validation modules in PHP and Javascript. The first framework will be responsible for server-side validation, and the second framework will validate data on the client side. They will be our workhorses and we can only find a way to connect these frameworks with each other.
Solving a problem is trivial - we create a class for declaring data validation rules. The point of this is that having a set of some rules we can apply them both on the server side and on the client side. It has its own specifics, but it boils down to correctly interpreting these rules in commands of a specific validation framework.
Now the validation will take place as follows:
1. We define the rules
2. The rules are passed to PHP wrapper class for use on the server side.
3. We translate the rules into a JavaScript array and pass them to the client, where at the right moment the data will be checked by the JavaScript wrapper class on the client side.
Example:
$validate=new Validate();
$validate//
->ruleUrl('url',' ')
->ruleEmail('email',' ',0);
if($_POST)
$validate->check($_POST,$errors);// $_POST, $errors
$js_main=$validate->js('main');// JavaScript
…..
function validate()// JavaScript
{
<?=$js_main?>
return main.checkForm($('#form'));//
}
You
can find the working example
here , and the
source code for the example here . Verification works on the client side with Javascript enabled, otherwise validation is performed only on the server side.