I am trying to get the preg_match '/[^0-9]/' thing below to validate or clear number only entries into a phone field. Am I on the right track as currently I cannot get it to work?
PHP Code:
public function validatePhone($phoneVal, $phoneName) {
if (strlen($phoneVal) <= 0) {
$this->setError($phoneName, "Phone Number Required");
} else if (!preg_match('/[^0-9]/', '',$phoneVal)) {
$this->setError($phoneName, "Valid Phone Number Required");
}
}
If you just want to validate that a string contains only digits:
PHP Code:
if(ctype_digit($string)) { // good } else { // bad }
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
"!" is essentially the same as "false ==". It inverts the Boolean result of what it precedes, so if is_numeric() returns false, then ! is_numeric() returns true; while if is_numeric() returns true, then ! is_numeric() returns false.
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
so not sure whether is_numeric is sufficient for validating phone numbers containing only numbers, I would go with preg_match.
Or ctype_digit(), which will be more efficient if that's all you need to test for.
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
is_numeric is not work, because it gives true for "6.5" too
so its best with preg_match only
Let me know if any issues
Thanks
DS
Or ctype_digit(), which will be more efficient if that's all you need to test for.
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
Last edited by chrisranjana; 06-22-2012 at 10:40 AM.
Reason: deleting this post as it contains "alpha" (http://stackoverflow.com/questions/1936504/php-regex-vs-ctype)
"!" is essentially the same as "false ==". It inverts the Boolean result of what it precedes, so if is_numeric() returns false, then ! is_numeric() returns true; while if is_numeric() returns true, then ! is_numeric() returns false.
Good ctype is good. I mean "late realization is always good"
Last edited by chrisranjana; 06-22-2012 at 10:08 AM.
Reason: edited
Bookmarks