diff --git a/README.md b/README.md index 9c2073f..1b0ca27 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,21 @@ if($v->validate()) { * `dateBefore` - Field is a valid date and is before the given date * `dateAfter` - Field is a valid date and is after the given date +## Adding Custom Validation Rules + +To add your own validation rule, use the `addRule` method with a rule +name, a custom callback or closure, and a error message to display in +case of an error. The callback provided should return boolean true or +false. + +``` +Valitron\Validation::addRule('alwaysFail', function($field, $value, +array $params) { + return false; +}, 'Everything you do is wrong. You fail.'); +``` + + ## Contributing 1. Fork it diff --git a/composer.json b/composer.json index eaa4c6e..7990087 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "vlucas/valitron", - "version": "1.0.0", + "version": "1.0.1", "type": "library", "description": "Simple, elegant, stand-alone validation library with NO dependencies", "keywords": ["validation", "validator", "valid"], diff --git a/src/Valitron/Validator.php b/src/Valitron/Validator.php index 2e44327..3282e4f 100644 --- a/src/Valitron/Validator.php +++ b/src/Valitron/Validator.php @@ -21,6 +21,8 @@ class Validator protected static $_rules = array(); protected static $_ruleMessages = array(); + const ERROR_DEFAULT = 'Invalid'; + /** * Setup validation @@ -470,13 +472,14 @@ class Validator /** * Register new validation rule callback */ - public static function addRule($name, $callback) + public static function addRule($name, $callback, $message = self::ERROR_DEFAULT) { if(!is_callable($callback)) { throw new \InvalidArgumentException("Second argument must be a valid callback. Given argument was not callable."); } static::$_rules[$name] = $callback; + static::$_ruleMessages[$name] = $message; } /** @@ -492,7 +495,7 @@ class Validator } // Ensure rule has an accompanying message - $message = isset(static::$_ruleMessages[$rule]) ? static::$_ruleMessages[$rule] : 'Invalid'; + $message = isset(static::$_ruleMessages[$rule]) ? static::$_ruleMessages[$rule] : self::ERROR_DEFAULT; // Get any other arguments passed to function $params = array_slice(func_get_args(), 2);