mirror of
https://github.com/vlucas/valitron.git
synced 2025-12-30 23:01:52 +00:00
Add example for adeding custom validation rules
This commit is contained in:
parent
85b359babe
commit
650db517b4
15
README.md
15
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
|
||||
|
||||
@ -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"],
|
||||
|
||||
@ -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);
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user