Javascript validation - server synchronization

In the interests of DRY , is there a structure / library / design template for specifying validation rules in one place and evaluating them both on the client side and on the server side? This seems like an obvious requirement, but I have not seen anything like it.

To clarify: I'm not interested in the server-side code that generates forms with the required javascript to validate it - I want the validation rules to be separate from the implementation on the client side and on the server side, for example. Request validation rules using the web interface.

Is there anything like that?

+5
source share
2 answers

. , .

, , , ajax , javascript eval.

, $rulesPHP rulesJS . , - .

class Validation
{

    protected static $rulesPHP = 
                       array( 
                             'positiveInteger' => array('($x === int($x))', '($x > 0)'),
                             'alphanumericString' => array(....)
                            );

    protected static $rulesJS = 
                       array(
                             'positiveInteger' => array('(x === int(x))', '(x > 0)'),
                             'alphanumericString' =>array(..... )
                            );       

    public static getValidatorPHP($type)
    {
         if (!isset($rulesPHP[$type])) return false;
         $exp = explode(' && ', self::$rulesPHP[$type]);

         return function($x) use ($exp)
         {
              return eval($exp);
         };
    }

    public static getJsRules($type)
    {
         if (!isset($rulesJS[$type])) return false;
         $exp = explode(' && ', self::$rulesJS[$type]);

         return $exp;
    }

}

:

  $posIntValidator = Validation::getValidatorPHP('positiveInteger');
  $posIntValidator($_POST['text1']);

Ajax ruleaccessor.php:

    $t = $_GET['type'];
    $out = Validation::getJsRules($t);
    echo $out;

JavaScript:

   function getValidator(type)
   {
       var rules;
       $.get('/ruleaccessor.php?type=' + type, function(in) {rules = in;});
       return function(x){return eval(rules);};
   }

   validatePosInt = getValidator('positiveInteger');
   validatePosInt($('#text1').val());

, , , . , .

, , , - .

+1

!

MVC, . , , "namespace.table.column" , JSON. css , (1), ".validate" JQuery, .

, , javascript!

(1): <input type="text" id="name" class="validate" />

:

, ?

JSON structure: validationObject = 
{
    type: 'integer',
    length: '4',
    min: '0',
    max: '10000'
}

function validate(input) {

    var validation = getValidationObject(); // Ajax call

    // perform type check

    // perform length check

    // perform min/max/disallowed content checks

}

, - .

+1

All Articles