add custom validation
334882
function (args) {
                args.HasError = false;
                args.ErrorMessage = "";

                var greaterThanToday = new VacationApproval.FromToDateValidator();
                greaterThanToday.FromOperator = 4 /* GreaterThanEqual */;
                greaterThanToday.From = new Date();
                greaterThanToday.ToOperator = 1 /* LessThanEqual */;
                greaterThanToday.To = this.Duration.From;
                greaterThanToday.IgnoreTime = true;

                if (!greaterThanToday.isAcceptable(this.Approval.ApprovedDate)) {
                    args.HasError = true;
                    args.ErrorMessage = greaterThanToday.customMessage({
                        "Format": "MM/DD/YYYY",
                        "Msg": "Date must be between ('{From}' - '{To}')."
                    }, greaterThanToday);
                    args.TranslateArgs = { TranslateId: greaterThanToday.tagName, MessageArgs: greaterThanToday, CustomMessage: greaterThanToday.customMessage };
                    return;
                }
            }
933762
public function addValidation($property, $validation, $options = array())
    {
        $validations = $this->getValidations($property);
        $validations[$validation] = $options;

        return $this;
    }
39080
def create_with_validation(cls, *args, **kwargs):
        
        ret_val = cls(*args, **kwargs)
        ret_val.full_clean()
        ret_val.save()
        return ret_val
1370108
def validate( self ):
        """"""
        klass = self.__class__

        for name in klass._fields:
            self.validate_field( name )
        return
154441
def validate(self, instance):
        """"""
        errors = {}
        self._validate_instance(instance, errors)

        if len(errors) > 0:
            raise ValidationException(errors)
1347317
function validation($data, $files) {
        global $DB;

        $errors = parent::validation($data, $files);

        // Add field validation check for duplicate shortname.
        if ($course = $DB->get_record('course', array('shortname' => $data['shortname']), '*', IGNORE_MULTIPLE)) {
            if (empty($data['id']) || $course->id != $data['id']) {
                $errors['shortname'] = get_string('shortnametaken', '', $course->fullname);
            }
        }

        // Add field validation check for duplicate idnumber.
        if (!empty($data['idnumber']) && (empty($data['id']) || $this->course->idnumber != $data['idnumber'])) {
            if ($course = $DB->get_record('course', array('idnumber' => $data['idnumber']), '*', IGNORE_MULTIPLE)) {
                if (empty($data['id']) || $course->id != $data['id']) {
                    $errors['idnumber'] = get_string('courseidnumbertaken', 'error', $course->fullname);
                }
            }
        }

        if ($errorcode = course_validate_dates($data)) {
            $errors['enddate'] = get_string($errorcode, 'error');
        }

        $errors = array_merge($errors, enrol_course_edit_validation($data, $this->context));

        $courseformat = course_get_format((object)array('format' => $data['format']));
        $formaterrors = $courseformat->edit_form_validation($data, $files, $errors);
        if (!empty($formaterrors) && is_array($formaterrors)) {
            $errors = array_merge($errors, $formaterrors);
        }

        // Add the custom fields validation.
        $handler = core_course\customfield\course_handler::create();
        $errors  = array_merge($errors, $handler->instance_form_validation($data, $files));

        return $errors;
    }
826615
def validate(self, value, model_instance):
        """"""
        if isinstance(value, six.string_types):
            super(JSONField, self).validate(value, model_instance)
            try:
                json.loads(value)
            except Exception as err:
                raise ValidationError(str(err))
426814
function valErrsChanged(newValue) {

                    // HTML5 custom validity
                    // http://dev.w3.org/html5/spec-preview/constraints.html#the-constraint-validation-api
                    if (domEl.setCustomValidity) {
                        /* only works in HTML 5. Maybe should throw if not available. */
                        domEl.setCustomValidity(newValue || '');
                    }

                    var errorHtml = newValue ? valTemplate.replace(/%error%/, newValue) : "";
                    var isRequired = info.getIsRequired();
                    var requiredHtml = isRequired ? requiredTemplate : '';
                    decorator.innerHTML = (isRequired || !!errorHtml) ? requiredHtml + errorHtml : "";
                }
999487
function CustomInput() {

        /**
         * ### CustomInput.input
         *
         * The HTML input element
         */
        this.input = null;

        /**
         * ### CustomInput.placeholder
         *
         * The placeholder text for the input form
         *
         * Some types preset it automatically
         */
        this.placeholder = null;

        /**
         * ### CustomInput.inputWidth
         *
         * The width of the input form as string (css attribute)
         *
         * Some types preset it automatically
         */
        this.inputWidth = null;

        /**
         * ### CustomInput.type
         *
         * The type of input
         */
        this.type = null;

        /**
         * ### CustomInput.preprocess
         *
         * The function that preprocess the input before validation
         *
         * The function receives the input form and must modify it directly
         */
        this.preprocess = null;

        /**
         * ### CustomInput.validation
         *
         * The validation function for the input
         *
         * The function returns an object like:
         *
         * ```javascript
         *  {
         *    value: 'validvalue',
         *    err:   'This error occurred' // If invalid.
         *  }
         * ```
         */
        this.validation = null;

        /**
         * ### CustomInput.validationSpeed
         *
         * How often (in milliseconds) the validation function is called
         *
         * Default: 500
         */
        this.validationSpeed = 500;

        /**
         * ### CustomInput.postprocess
         *
         * The function that postprocess the input after validation
         *
         * The function returns the postprocessed valued
         */
        this.postprocess = null;

        /**
         * ### CustomInput.params
         *
         * Object containing extra validation params
         *
         * This object is populated by the init function
         */
        this.params = {};

        /**
         * ### CustomInput.errorBox
         *
         * An HTML element displayed when a validation error occurs
         */
        this.errorBox = null;

        /**
         * ### CustomInput.mainText
         *
         * A text preceeding the custom input
         */
        this.mainText = null;

        /**
         * ### CustomInput.hint
         *
         * An additional text with information about the input
         *
         * If not specified, it may be auto-filled, e.g. '*'.
         *
         * @see CustomInput.texts.autoHint
         */
        this.hint = null;

        /**
         * ### CustomInput.requiredChoice
         *
         * If TRUE, the input form cannot be left empty
         *
         * Default: TRUE
         */
        this.requiredChoice = null;

        /**
         * ### CustomInput.timeBegin
         *
         * When the first character was inserted
         */
        this.timeBegin = null;

        /**
         * ### CustomInput.timeEnd
         *
         * When the last character was inserted
         */
        this.timeEnd = null;

        /**
         * ### CustomInput.checkbox
         *
         * A checkbox element for an additional action
         */
        this.checkbox = null;

        /**
         * ### CustomInput.checkboxText
         *
         * The text next to the checkbox
         */
        this.checkboxText = null;

        /**
         * ### CustomInput.checkboxCb
         *
         * The callback executed when the checkbox is clicked
         */
        this.checkboxCb = null;
    }
427612
def validate(cls, **kwargs):
        '''  '''
        # errors can store multiple errors
        # obj is an instance in case validation succeeds
        # redis is needed for database validation
        errors = ValidationErrors()
        obj = cls()
        redis = cls.get_redis()

        # Check the fields
        for fieldname, field in obj.proxy:
            if not field.fillable:
                value = field.default
            else:
                try:
                    value = field.validate(kwargs.get(fieldname), redis)
                except BadField as e:
                    errors.append(e)
                    continue

            setattr(
                obj,
                fieldname,
                value
            )

        # Check for custom validation rules
        for fieldname in dir(cls):
            rule = getattr(cls, fieldname)

            if hasattr(rule, '_is_validation_rule') and rule._is_validation_rule:
                try:
                    rule(obj)
                except BadField as e:
                    errors.append(e)

        # Trigger errors if any
        if errors.has_errors():
            raise errors

        # Return the object with the new data set
        return obj
1358814
public function addValidation($validation, $value = null)
    {
        if (false === isset($this->validation[$validation])) {
            $this->validation[$validation] = [];
        }

        $this->validation[$validation][] = $value;

        return $this;
    }
327809
protected function validate() {
		$msg = $this->getMessages();

		// Validate nonce.
		if ( ! isset( $_POST['set_key_auth'] ) || ! check_ajax_referer( 'boldgrid_set_key', 'set_key_auth', false ) ) {
			wp_send_json_error( array( 'message' => $msg->nonce ) );
		}

		// Validate user input.
		if ( empty( $_POST['api_key'] ) ) {
			wp_send_json_error( array( 'message' => $msg->error ) );
		}

		// Validate key.
		$valid = new Library\Key\Validate( sanitize_text_field( $_POST['api_key'] ) );
		if ( ! $valid->getValid() ) {
			wp_send_json_error( array( 'message' => $msg->error ) );
		}

		return $valid->getHash();
	}
661652
function(attrs, options) {
        if (options.silent || !this.validate) {
          return;
        }
        attrs = _.extend({}, this.attributes, attrs);
        this.validate(attrs);
      }
449810
function addValidator(name, validator, params) {
    var _this = this;
    var validators = validator instanceof Array ? validator : [validator];
    var validate = void 0;

    if (typeof validator === 'string') {
        validate = function validate() /*value, arg, options*/{
            return _this[validator].apply({ alias: name, _this: _this }, arguments);
        };
    } else {
        validate = function validate(value /*arg, options*/) {
            var args = Array.prototype.slice.call(arguments, 2);
            var arg1 = arguments[1];
            var arg2 = arguments[2];
            var _this2 = this && this._this || _this;
            var isSimpleArgsFormat = _this2[name][SIMPLE_ARGS_FORMAT] || _this2[SIMPLE_ARGS_FORMAT];
            var isOneOptionsArg = _this2[name][ONE_OPTIONS_ARG] || _this2[ONE_OPTIONS_ARG];
            var options = !isOneOptionsArg && isPlainObject(arg2) ? arg2 : {};

            if (arg1 != null && typeof arg1 !== 'boolean') {
                if (isPlainObject(arg1)) {
                    options = arg1;
                } else {
                    options[_this2[name][ARG] || _this2[ARG]] = arg1;

                    if (!isSimpleArgsFormat) {
                        args.shift();
                    }
                }
            }

            for (var i = 0; i < validators.length; i++) {
                var base = validators[i];

                switch (typeof base === 'undefined' ? 'undefined' : _typeof(base)) {
                    case 'function':
                        validator = validatorWrapper(_this2, name, base);break;

                    case 'string':
                        validator = _this2[base];break;

                    case 'object':
                        validator = _this2[base[0]];
                        options = assign({}, options, base[1]);
                }

                var error = validator.apply(this, [value, options].concat(args));

                if (error) {
                    return error;
                }
            }
        };
    }

    assign(validate, params);

    validate.curry = function () /*arg, options*/{
        var _arguments = arguments;
        //Partial application
        return function (value) {
            return validate.apply(_this, [value].concat(Array.prototype.slice.call(_arguments)));
        };
    };

    _this[name] = validate;
}
1113914
def validate(self, value) :
        """"""
        for v in self.validators :
            v.validate(value)
        return True
801360
private final function loadValidation(): void
    {
        $this->validation = new Validation();

        $rules = $this->config->get('validation.rules');
        if ($rules != null) {
            $this->validation->setRules($rules);
        }
    }
1193584
function addValidElements(validElements) {
        var ei, el, ai, al, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder,
          prefix, outputName, globalAttributes, globalAttributesOrder, key, value,
          elementRuleRegExp = /^([#+\-])?([^\[!\/]+)(?:\/([^\[!]+))?(?:(!?)\[([^\]]+)\])?$/,
          attrRuleRegExp = /^([!\-])?(\w+::\w+|[^=:<]+)?(?:([=:<])(.*))?$/,
          hasPatternsRegExp = /[*?+]/;

        if (validElements) {
          // Split valid elements into an array with rules
          validElements = split(validElements, ',');

          if (elements['@']) {
            globalAttributes = elements['@'].attributes;
            globalAttributesOrder = elements['@'].attributesOrder;
          }

          // Loop all rules
          for (ei = 0, el = validElements.length; ei < el; ei++) {
            // Parse element rule
            matches = elementRuleRegExp.exec(validElements[ei]);
            if (matches) {
              // Setup local names for matches
              prefix = matches[1];
              elementName = matches[2];
              outputName = matches[3];
              attrData = matches[5];

              // Create new attributes and attributesOrder
              attributes = {};
              attributesOrder = [];

              // Create the new element
              element = {
                attributes: attributes,
                attributesOrder: attributesOrder
              };

              // Padd empty elements prefix
              if (prefix === '#') {
                element.paddEmpty = true;
              }

              // Remove empty elements prefix
              if (prefix === '-') {
                element.removeEmpty = true;
              }

              if (matches[4] === '!') {
                element.removeEmptyAttrs = true;
              }

              // Copy attributes from global rule into current rule
              if (globalAttributes) {
                for (key in globalAttributes) {
                  attributes[key] = globalAttributes[key];
                }

                attributesOrder.push.apply(attributesOrder, globalAttributesOrder);
              }

              // Attributes defined
              if (attrData) {
                attrData = split(attrData, '|');
                for (ai = 0, al = attrData.length; ai < al; ai++) {
                  matches = attrRuleRegExp.exec(attrData[ai]);
                  if (matches) {
                    attr = {};
                    attrType = matches[1];
                    attrName = matches[2].replace(/::/g, ':');
                    prefix = matches[3];
                    value = matches[4];

                    // Required
                    if (attrType === '!') {
                      element.attributesRequired = element.attributesRequired || [];
                      element.attributesRequired.push(attrName);
                      attr.required = true;
                    }

                    // Denied from global
                    if (attrType === '-') {
                      delete attributes[attrName];
                      attributesOrder.splice(inArray(attributesOrder, attrName), 1);
                      continue;
                    }

                    // Default value
                    if (prefix) {
                      // Default value
                      if (prefix === '=') {
                        element.attributesDefault = element.attributesDefault || [];
                        element.attributesDefault.push({ name: attrName, value: value });
                        attr.defaultValue = value;
                      }

                      // Forced value
                      if (prefix === ':') {
                        element.attributesForced = element.attributesForced || [];
                        element.attributesForced.push({ name: attrName, value: value });
                        attr.forcedValue = value;
                      }

                      // Required values
                      if (prefix === '<') {
                        attr.validValues = makeMap(value, '?');
                      }
                    }

                    // Check for attribute patterns
                    if (hasPatternsRegExp.test(attrName)) {
                      element.attributePatterns = element.attributePatterns || [];
                      attr.pattern = patternToRegExp(attrName);
                      element.attributePatterns.push(attr);
                    } else {
                      // Add attribute to order list if it doesn't already exist
                      if (!attributes[attrName]) {
                        attributesOrder.push(attrName);
                      }

                      attributes[attrName] = attr;
                    }
                  }
                }
              }

              // Global rule, store away these for later usage
              if (!globalAttributes && elementName == '@') {
                globalAttributes = attributes;
                globalAttributesOrder = attributesOrder;
              }

              // Handle substitute elements such as b/strong
              if (outputName) {
                element.outputName = elementName;
                elements[outputName] = element;
              }

              // Add pattern or exact element
              if (hasPatternsRegExp.test(elementName)) {
                element.pattern = patternToRegExp(elementName);
                patternElements.push(element);
              } else {
                elements[elementName] = element;
              }
            }
          }
        }
      }