简体   繁体   中英

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 -- ie 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

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM