Skip to content
Browse files

Adding a validation rule for checking natural numbers

  • Loading branch information...
1 parent 4fd45c0 commit 7546be63948d658e33f6d9017172cbb9c8395a4b @sarahhenkens sarahhenkens committed
Showing with 33 additions and 0 deletions.
  1. +20 −0 lib/Cake/Test/Case/Utility/ValidationTest.php
  2. +13 −0 lib/Cake/Utility/Validation.php
View
20 lib/Cake/Test/Case/Utility/ValidationTest.php
@@ -1961,6 +1961,26 @@ public function testNumeric() {
}
/**
+ * 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->assertTrue(Validation::naturalNumber('2'));
+ $this->assertTrue(Validation::naturalNumber(49));
+ $this->assertTrue(Validation::naturalNumber('0', true));
+ $this->assertTrue(Validation::naturalNumber(0, true));
+ }
+
+/**
* testPhone method
*
* @return void
View
13 lib/Cake/Utility/Validation.php
@@ -564,6 +564,19 @@ public static function numeric($check) {
}
/**
+ * Checks if a value is a natural value.
+ *
+ * @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.
*
* @param mixed $check Value to check (string or array)

0 comments on commit 7546be6

Please sign in to comment.
Something went wrong with that request. Please try again.