Add example for adeding custom validation rules

This commit is contained in:
Vance Lucas 2013-02-06 14:12:36 -06:00
parent 85b359babe
commit 650db517b4
3 changed files with 21 additions and 3 deletions

View File

@ -93,6 +93,21 @@ if($v->validate()) {
* `dateBefore` - Field is a valid date and is before the given date * `dateBefore` - Field is a valid date and is before the given date
* `dateAfter` - Field is a valid date and is after 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 ## Contributing
1. Fork it 1. Fork it

View File

@ -1,6 +1,6 @@
{ {
"name": "vlucas/valitron", "name": "vlucas/valitron",
"version": "1.0.0", "version": "1.0.1",
"type": "library", "type": "library",
"description": "Simple, elegant, stand-alone validation library with NO dependencies", "description": "Simple, elegant, stand-alone validation library with NO dependencies",
"keywords": ["validation", "validator", "valid"], "keywords": ["validation", "validator", "valid"],

View File

@ -21,6 +21,8 @@ class Validator
protected static $_rules = array(); protected static $_rules = array();
protected static $_ruleMessages = array(); protected static $_ruleMessages = array();
const ERROR_DEFAULT = 'Invalid';
/** /**
* Setup validation * Setup validation
@ -470,13 +472,14 @@ class Validator
/** /**
* Register new validation rule callback * 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)) { if(!is_callable($callback)) {
throw new \InvalidArgumentException("Second argument must be a valid callback. Given argument was not callable."); throw new \InvalidArgumentException("Second argument must be a valid callback. Given argument was not callable.");
} }
static::$_rules[$name] = $callback; static::$_rules[$name] = $callback;
static::$_ruleMessages[$name] = $message;
} }
/** /**
@ -492,7 +495,7 @@ class Validator
} }
// Ensure rule has an accompanying message // 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 // Get any other arguments passed to function
$params = array_slice(func_get_args(), 2); $params = array_slice(func_get_args(), 2);