Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Something along these lines would probably be good:</p> <pre><code>&lt;?php $validation = Array( "field1" =&gt; Array( // "field1" is the name of the input field "required" =&gt; true, // or false "minlength" =&gt; 5, // use 0 for no minimum "maxlength" =&gt; 10, // use 9999 (or other high number) for no maximum "regex" =&gt; "^[a-zA-Z0-9]+$" // use empty string for no regex ), "field2" =&gt; ....... .... ); if( $_POST) { foreach($validation as $k=&gt;$v) { if( !isset($_POST[$k])) { if( $v['required']) die("Field ".$k." is required"); } else { $l = strlen($_POST[$k]); if( $l &lt; $v['minlength']) die("Field ".$k." too short"); if( $l &gt; $v['maxlength']) die("Field ".$k." too long"); if( !preg_match("(".$v['regex'].")",$_POST[$k])) die("Field ".$k." incorrect format"); } } // all ok! } ?&gt; &lt;script type="text/javascript"&gt; (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 &lt; r.minlength) return die("Field "+i+" too short"); if( s &gt; r.maxlength) return die("Field "+i+" too short"); if( !s.match(new RegExp(r.regex))) return die("Field "+i+" incorrect format"); } } return true; }; })(&lt;?=json_encode($validation)?&gt;); &lt;/script&gt; </code></pre> <p>As you can see, the general idea is to define a set of rules, then the magic happens in the <code>json_encode($validation)</code> - 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!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload