Reputation: 755
I would like to "validate" my posted phone number. I don't really care about the format, i just want to use only numbers and some chars. I tried this code, but if i type at least one number to my string then string will be valid. (for ex.: asdafadas-1asd will be valid) How to fix this?
$phonebool=true;
if (!(strcspn($_POST['phone'], '0123456789-/ ') != strlen($_POST['phone']) )){
$_SESSION['phone_err']='Only numbers and -/';
$phonebool=false;
}
thank you.
Upvotes: 1
Views: 16182
Reputation: 13785
Working code
if (!(preg_match("([0-9-]+)", $_POST['phone']) != strlen($_POST['phone']) )){
$_SESSION['phone_err']='Only numbers and -/';
$phonebool=false;
}
Upvotes: 1
Reputation: 61
You should use a regular expression instead, something like:
/^[0-9\/-]+$/
Otherwise have a look at libphonenumber - it seems that a php port exists: https://github.com/davideme/libphonenumber-for-PHP
Examples:
var_dump(preg_match('/^[0-9\/-]+$/', 'asdafadas-1asd'));
=> int(0)
var_dump(preg_match('/^[0-9\/-]+$/', '12/34-56'));
=> int(1)
Upvotes: 3
Reputation: 91
Try this:
$phonebool=true;
if (!(preg_match("([0-9-]+)", $_POST['phone']) != strlen($_POST['phone']) )){
$_SESSION['phone_err']='Only numbers and -/';
$phonebool=false;
}
Upvotes: 0
Reputation: 708
one recommendation: use javascript/jquery to validate your forms, so the users can correct right away before submit.
Upvotes: 0
Reputation: 13785
Try This .
if(ereg("^[0-9]{3}-[0-9]{3}-[0-9]{4}$", $number) ) {
echo "works";
} else {
$errmsg = 'Please enter your valid phone number';
}
Upvotes: 2