Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recommendations on sharing validation rules between Javascript and PHP?

We're in the process of writing a new form which our front-end coder has included lots and lots of JavaScript validation (technically, jQuery Tools validation).

I'm writing the PHP server-side part of the process, and of course, my own code will be doing its own validation of the data received.

Rather than have to maintain two sets of validation rules -- jQuery and PHP -- do you have any recommendations about a way to create a central list of validation rules -- i.e. field X must be size > 1 and < 10, etc. -- so I could change a validation rule in a single file or database table that would then be passed both to PHP and to jQuery?

For instance, change that same rule I mentioned above "field X must be size > 1 and < 10" to "field X must be size > 3 and < 5" and all I would have to do is edit a file or database table and both PHP and jQuery would retrieve and parse that data accordingly?

Thanks in advance for your help,

Phil

like image 425
PhilGA Avatar asked Apr 16 '12 23:04

PhilGA


People also ask

Do PHP supports validation?

PHP validates the data at the server-side, which is submitted by HTML form. You need to validate a few things: Empty String. Validate String.

What is the importance of validation in PHP?

Importance of PHP Form Validation Validates data as float, & translates to float on success. Validates data as integer, & translates to integer on success.

What is validation rule in PHP?

There are two types of validation are available in PHP. They are as follows − Client-Side Validation − Validation is performed on the client machine web browsers. Server Side Validation − After submitted by data, The data has sent to a server and perform validation checks in server machine.


2 Answers

Something along these lines would probably be good:

<?php
$validation = Array(
    "field1" => Array( // "field1" is the name of the input field
        "required" => true, // or false
        "minlength" => 5, // use 0 for no minimum
        "maxlength" => 10, // use 9999 (or other high number) for no maximum
        "regex" => "^[a-zA-Z0-9]+$" // use empty string for no regex
    ),
    "field2" => .......
    ....
);
if( $_POST) {
    foreach($validation as $k=>$v) {
        if( !isset($_POST[$k])) {
            if( $v['required']) die("Field ".$k." is required");
        }
        else {
            $l = strlen($_POST[$k]);
            if( $l < $v['minlength']) die("Field ".$k." too short");
            if( $l > $v['maxlength']) die("Field ".$k." too long");
            if( !preg_match("(".$v['regex'].")",$_POST[$k])) die("Field ".$k." incorrect format");
        }
    }
    // all ok!
}
?>
<script type="text/javascript">
    (function(rules) {
        var die = function(str) {alert(str); return false;};
        document.getElementById('myForm').onsubmit = function() {
            var elms = this.elements, i, it, r, s;
            for( i in rules) {
                r = rules[i];
                it = elms.namedItem(i);
                if( typeof it == "undefined") {
                    if( r.required) return die("Field "+i+" is required");
                }
                else {
                    s = it.length;
                    if( s < r.minlength) return die("Field "+i+" too short");
                    if( s > r.maxlength) return die("Field "+i+" too short");
                    if( !s.match(new RegExp(r.regex))) return die("Field "+i+" incorrect format");
                }
            }
            return true;
        };
    })(<?=json_encode($validation)?>);
</script>

As you can see, the general idea is to define a set of rules, then the magic happens in the json_encode($validation) - this passes the rules down into the JavaScript environment. You still have to duplicate the validation code to have it run in PHP and in JS, but at least now you can add more rules without having to change the code in two places. Hope this helps!

like image 72
Niet the Dark Absol Avatar answered Oct 06 '22 00:10

Niet the Dark Absol


The Nette framework does this: http://doc.nette.org/en/forms

The whole form and the validation rules are defined in a PHP file. The framework then generates HTML code with javascript validation and after submitting it performs the server-side validation.

You can even use the Forms part of the framework separately.

like image 40
Tereza Tomcova Avatar answered Oct 05 '22 23:10

Tereza Tomcova