Gdn_Validation::validateRule PHP Method

validateRule() public static method

Execute a single validation rule and return its result.
public static validateRule ( mixed $Value, string $FieldName, string | array $Rule, string $CustomError = false ) : boolean | string
$Value mixed The value to validate.
$FieldName string The name of the field to put into the error result.
$Rule string | array The rule to validate which can be one of the following. - string: The name of a function used to validate the value. - 'regex:': The regular expression used to validate the value. - array: An array with the following keys: - Name: The name of the function used to validate. - Args: An argument to pass to the function after the value.
$CustomError string A custom error message.
return boolean | string One of the following - TRUE: The value passed validation. - string: The error message associated with the error.
    public static function validateRule($Value, $FieldName, $Rule, $CustomError = false)
    {
        // Figure out the type of rule.
        if (is_string($Rule)) {
            if (stringBeginsWith($Rule, 'regex:', true)) {
                $RuleName = 'validateregex';
                $Args = substr($Rule, 6);
            } elseif (stringBeginsWith($Rule, 'function:', true)) {
                $RuleName = substr($Rule, 9);
            } else {
                $RuleName = $Rule;
            }
        } elseif (is_array($Rule)) {
            $RuleName = val('Name', $Rule);
            $Args = val('Args', $Rule);
        }
        if (!isset($Args)) {
            $Args = null;
        }
        if (function_exists($RuleName)) {
            $Result = $RuleName($Value, $Args);
            if ($Result === true) {
                return true;
            } elseif ($CustomError) {
                return $CustomError;
            } elseif (is_string($Result)) {
                return $Result;
            } else {
                return sprintf(T($RuleName), T($FieldName));
            }
        } else {
            return sprintf('Validation does not exist: %s.', $RuleName);
        }
    }

Usage Example

Example #1
0
 /**
  * Validates a rule on the form and adds its result to the errors collection.
  *
  * @param string $FieldName The name of the field to validate.
  * @param string|array $Rule The rule to validate against.
  * @param string $CustomError A custom error string.
  * @return bool Whether or not the rule succeeded.
  *
  * @see Gdn_Validation::ValidateRule()
  */
 public function validateRule($FieldName, $Rule, $CustomError = '')
 {
     $Value = $this->getFormValue($FieldName);
     $Valid = Gdn_Validation::validateRule($Value, $FieldName, $Rule, $CustomError);
     if ($Valid === true) {
         return true;
     } else {
         $this->addError('@' . $Valid, $FieldName);
         return false;
     }
 }