Skip to content

Commit

Permalink
Add Validator::regex()
Browse files Browse the repository at this point in the history
Foo
  • Loading branch information
Michael Hoffmann committed Feb 25, 2017
1 parent 4180750 commit a28467c
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/Validation/Validator.php
Expand Up @@ -1684,6 +1684,25 @@ public function isPresenceRequired($field, $newRecord)
return !$this->_checkPresence($this->field($field), $context);
}

/**
* Returns whether or not a field matches against a regular expression.
*
* @param string $field Field name.
* @param string $regex Regular expression.
* @param string|null $message The error message when the rule fails.
* @param string|callable|null $when Either 'create' or 'update' or a callable that returns
* true when the validation rule should be applied.
* @return bool
*/
public function regex($field, $regex, $message = null, $when = null)
{
$extra = array_filter(['on' => $when, 'message' => $message]);

return $this->add($field, 'regex', $extra + [
'rule' => ['custom', $regex]
]);
}

/**
* Returns false if any validation for the passed rule set should be stopped
* due to the field missing in the data array
Expand Down
13 changes: 13 additions & 0 deletions tests/TestCase/Validation/ValidatorTest.php
Expand Up @@ -1845,6 +1845,19 @@ public function testHasAtMost()
$this->assertNotEmpty($validator->errors(['things' => ['_ids' => [1, 2, 3, 4]]]));
}

/**
* Tests the regex proxy method
*
* @return void
*/
public function testRegex()
{
$validator = new Validator();
$this->assertProxyMethod($validator, 'regex', '/(?<!\\S)\\d++(?!\\S)/', ['/(?<!\\S)\\d++(?!\\S)/'], 'custom');
$this->assertEmpty($validator->errors(['username' => '123']));
$this->assertNotEmpty($validator->errors(['username' => 'Foo']));
}

/**
* Tests that a rule in the Validator class exists and was configured as expected.
*
Expand Down

0 comments on commit a28467c

Please sign in to comment.