Merge pull request #662 from jellehenkens/2.2-validation-natural-number

Adding validation rule for natural numbers
This commit is contained in:
Mark Story 2012-05-27 11:01:31 -07:00
commit 4485f597b7
2 changed files with 34 additions and 0 deletions

View file

@ -1960,6 +1960,27 @@ class ValidationTest extends CakeTestCase {
$this->assertTrue(Validation::numeric('2.2'));
}
/**
* testNaturalNumber method
*
* @return void
*/
public function testNaturalNumber() {
$this->assertFalse(Validation::naturalNumber('teststring'));
$this->assertFalse(Validation::naturalNumber('5.4'));
$this->assertFalse(Validation::naturalNumber(99.004));
$this->assertFalse(Validation::naturalNumber('0,05'));
$this->assertFalse(Validation::naturalNumber('-2'));
$this->assertFalse(Validation::naturalNumber(-2));
$this->assertFalse(Validation::naturalNumber('0'));
$this->assertFalse(Validation::naturalNumber('050'));
$this->assertTrue(Validation::naturalNumber('2'));
$this->assertTrue(Validation::naturalNumber(49));
$this->assertTrue(Validation::naturalNumber('0', true));
$this->assertTrue(Validation::naturalNumber(0, true));
}
/**
* testPhone method
*

View file

@ -563,6 +563,19 @@ class Validation {
return is_numeric($check);
}
/**
* Checks if a value is a natural number.
*
* @param string $check Value to check
* @param boolean $allowZero Set true to allow zero, defaults to false
* @return boolean Success
* @see http://en.wikipedia.org/wiki/Natural_number
*/
public static function naturalNumber($check, $allowZero = false) {
$regex = $allowZero ? '/^(?:0|[1-9][0-9]*)$/' : '/^[1-9][0-9]*$/';
return self::_check($check, $regex);
}
/**
* Check that a value is a valid phone number.
*