I am trying to validate my registration form, and one of my validations doesn't work. I want to echo a error message if the first name is over 20 characters long. I am using the code
} else if($_POST["mem_first_name"] >20) {
$errors[] = 'Sorry but your First name is limited to 20 Characters each';
}
However no error is shown if more than 20 characters are entered. However if I use the same code but change it to less than like this
} else if($_POST["mem_first_name"] <20) {
$errors[] = 'Sorry but your First name is limited to 20 Characters each';
}
Then it works, is there a simple fix?
if(strlen($_POST["mem_first_name"]) > 20)
Use strlen() function
} else if(strlen($_POST["mem_first_name"]) >20) {
$errors[] = 'Sorry but your First name is limited to 20 Characters each';
}
How about using the strlen() function, for counting strings? It is stable and appropriate way of counting number of characters IMO
} else if(strlen($_POST["mem_first_name"]) >20) {
$errors[] = 'Sorry but your First name is limited to 20 Characters each';
}
You have to use strlen() function for string length checks. Also, be aware that if you need multibyte encoding support, you should switch to using mb_strlen().
var_dump(strlen('bär')); // int(4) - byte length
var_dump(mb_strlen('bär', 'utf8')); // int(3) - character length
Related
This is my code to check if the field is empty and it works fine, however i want to check for both, if its empty and if its got less than 10 characters
<pre>
if(empty($_POST['comments'])){ $errors[]="Please enter a comment."; }
</pre>
I tried this
<pre>
if(empty($_POST['comments'])){ $errors[]="Please enter a comment."; }
if(strlen($_POST['comments']) > 10){ $errors[]="Please enter a comment."; }
</pre>
However this then made neither work so i tried which had the same result with neither of them working
<pre>
if(empty($_POST['comments']) && strlen($_POST['comments']) > 10)){ $errors[]="Your
comment must be longer than 10 characters."; }
</pre>
I have tried mb_strlen as well but that changed nothing.
Your logic is a bit off. You're currently adding the error if the string is empty and longer than 10 characters (which would be a paradox.)
You need to check if the string is empty or less then 10 characters.
Try this:
if (empty($_POST['comments']) || strlen($_POST['comments']) < 10) {
$errors[] = "Your comment must be longer than 10 characters.";
}
That condition checks if the string is either empty or if the string has less < than 10 characters.
&& means and
|| means or
< means less than
> means greater than
You can read more about logical and comparison operators in the manual.
I'm adding some very basic validation to a "name" form field. Generally, it's impossible to actually validate a name, but I figured I could at least verify that it's not empty, greater than maybe 2 characters (Al is the shortest name I can think of), and that those characters aren't just empty space.
Here's the conditionals I'm using:
// Check length of name field
if(!isset($name) || $name < 2 || (strlen($name) > 0 && strlen(trim($name)) == 0)) {
// Name field only spaces
if((strlen($name) > 0 && strlen(trim($name)) == 0) || trim($name) == '') {
$errors['name'] = "Please enter a real name...";
}
// Name too short
else {
$errors['name'] = "Are you sure <strong>".htmlspecialchars($name)."</strong> is your name?";
}
$msg_type = "error";
}
However, when I run this with a valid name, I get the "Name too short" error. I know it's got to be a problem with how I'm combining the conditionals, but I can't figure out where that problem lies.
$name < 2 doesn't work. You're trying to use strlen($name) < 2.
Well, there is a tool called regex which people have invented for string matching and it could be pretty conveniently used for validation cases like yours. If you want to validate a word let's say with at least 2 characters of length, you could do the following:
if(!preg_match('/\b\w{2,}/', $name)) {
$errors['name'] = "Are you sure <strong>".htmlspecialchars($name)."</strong> is your name?";
}
Where:
\b: word boundary
\w: word character
{2,}: two or more times for the word character
I have a password validation script for the signup process and it works OK if I don't set a maximum length limit. If I add a maximum limit of 32 it ignores the validation, creating the account, even if I have more than 32 characters.
Working script:
if (preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $_POST["password"]) === 0)
{
echo "The password must contain lower case characters, upper case characters and numbers. It's length should be between 8 and 32 characters.";
}
Not working script:
if (preg_match("/^.*(?=.{8,32})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $_POST["password"]) === 0)
{
echo "The password must contain lower case characters, upper case characters and numbers. It's length should be between 8 and 32 characters.";
}
Please let me know before downrating so that I can edit my question. Thanks!
To limit the length, just edit your regular expression. You're already half way there.
/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{8,32}$/
Demo: http://regex101.com/r/nK5yY6
Doing it in one big regex is a bit of a code maintenance nightmare. Splitting it up is far easier to figure out for someone else looking at your code, and it allows you to give more specific error messages as well.
This solution works for me , try it :
$password = $_POST["password"];
$uppercase = preg_match('#[A-Z]#', $password);
$lowercase = preg_match('#[a-z]#', $password);
$number = preg_match('#[0-9]#', $password);
$length = preg_match("#^.{8,32}$#" , $password);
if(!$uppercase || !$lowercase || !$number || !$length ) {
echo "The password must contain lower case characters, upper case characters and numbers. It's length should be between 8 and 32 characters.";
}
if (preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $_POST["password"]) === 0 || strlen($_POST['password']) < 8 || strlen($_POST['password']) > 32 )
{
echo "The password must contain lower case characters, upper case characters and numbers. It's length should be between 8 and 32 characters.";
}
If you are looking for password with atleast 1 digit and 1 alphabet please try this:
^.*(?=.{8,32})(?=.*\d)(?=.*[a-zA-Z]).*$
function sendSms($toPhone,$message){
$toPhone=intval(trim($toPhone));
if(strlen($toPhone)== 8 && $toPhone{0}==9){
//sending sms
}else{
return "error";
}
}
I am trying to validate mobile numbers for sending SMS. The first line trims the phone number string and then converts it to an integer. In the if statement, I want to make sure that the number length is 8 digits and it begins with 9. This function always goes for the else even if the number is correct( 8 digits and begins with 9). What could be the issue here.
Why not regex?
$valid = preg_match('/^9[0-9]{7}$/', trim($phone));
You can remove from $toPhone all not digits
function sendSms($toPhone,$message){
$_phone = '';
for ($i = 0; $i < strlen($toPhone); $i++)
{
if (is_numeric($toPhone[$i]))
$_phone .= $toPhone[$i];
}
if(strlen($_phone)== 8 && $_phone[0]=='9'){
//sending sms
}else{
return "error";
}
}
After you converted the phone number to an integer with $toPhone=intval(trim($toPhone));,, you can't access the digits in the way you are trying with $toPhone{0}, because you operate on a number and not on a string any more.
See this isolated example:
$number = 987654321;
var_dump($number{0}); //NULL
However, substr would be capable of doing this:
$number = 987654321;
var_dump(substr($number, 0, 1)); //string(1) "9"
Converting a whole number to integer isn't a good idea anyways, because users might enter the number with spaces in between or signs like + and /. Better search for an already existing approach to validate phone numbers.
Take a look here, where the topic "validate mobile phone numbers" is covered in more detail: A comprehensive regex for phone number validation
You convert variable to integer and apparently $toPhone[0] works on strings only.
The same function without intval() works as you wanted.
function sendSms($toPhone, $message)
{
$toPhone = trim($toPhone);
if(strlen($toPhone) == 8 && $toPhone[0] == 9){
//sending sms
} else {
return "error";
}
}
I am trying to validate a phone number and require it to have 10 digits only no spaces or special characters allowed (example: 0123456789) and the same goes with zip code except 5 digits only (example: 01234).
This is what I have for the phone number field so far.
$phone = stripslashes($_POST['phone']);
if(!$phone || $phone == "Phone Number*")
{
$error .= "Please enter your phone number.<br />";
}
The next if statement should retrieve an error similar to "Please enter a valid phone number. Example: "0123456789".
If you don't want to use regular expressions, take a look at ctype_digit
For example:
if(strlen($phone)==10 && ctype_digit($phone)) {
//valid
} else {
//invalid
}
I can't testify to whether this will be faster or slower than regular expressions, but I would reckon it's probably moot. It's more or less what makes the most sense to you.
You can try regex here:
if(preg_match('/^[0-9]{10}$/', $phone)){
// valid
}else{
// Not valid
}
Something a little like that will ensure only numerical characters and 10 of them. Just change the 10 to 5 for zip code.
One more thing if $_POST['phone'] is not set when you access it you will get a E_NOTICE so just a tip here for you do:
$phone = isset($_POST['phone']) ? stripslashes($_POST['phone']) : null;
if(!$phone) // ERROR
$phone = stripslashes($_POST['phone']);
if(!$phone || $phone == "Phone Number*")
{
$error .= "Please enter your phone number.<br />";
}
if(!preg_match('/^\d{10}$/', $phone)) $error .= "Please enter phone number as ##########.<br />";
And for zip code
if(!preg_match('/^\d{5}$/', $zip)) $error .= "Please enter your zip code as #####.<br />";
Keep in mind that this will not allow foreign zip codes (which may be of different lengths or include letters)
Just some other suggestions too (to prevent unnecessary error messages)
You may want to process your user input such that 123-456-7890 becomes 1234567890 by doing something like
preg_replace('/[^\d]/','',$input)
Maybe do a trim($input) to strip leading/trailing whitespace
Finally, is there any particular reason you are using stripslashes on $_POST['phone']?
If they are all digits like you expect, then this shouldnt be necessary.
If they aren't all digits, then you will throw an error regardless
how about:
function check($number,$length)
{
if(ctype_digit ($number) && strlen($number)==$length)
return true;
else
return false;
}
if(check("1234",4))
echo "ok";
else
echo "Please enter a valid phone number. Example: "0123456789";
Well, this an old post but I will throw in some comments here anyway.
1) you should really not force the user to put in the right numbers, of course your validation on the front end will cover this but never assume it to be case coming into the "backend" .
Consider the following instead of putting the on the user:
// remove chars
$number = preg_replace('/[\D]/', '', $number);
//unit test sanitizer
filter_var($number, FILTER_SANITIZE_NUMBER_INT)
// check number
preg_match('/^[0-9]{10}$/', $zip)
Example : Read in user input if enough digits entered in look up closest matching zipcode etc.. (I actually used this on a site once) Of course setting the frontend to check is useful, but in case that fails .
$number = 'z 02012s';
// remove chars
$number = preg_replace('/[\D]/', '', $number);
//unit test sanitizer
$number = filter_var($number, FILTER_SANITIZE_NUMBER_INT);
// check number
if (preg_match('#^[0-9]{5}$#', $number) === 1) {
//(optional) lookup closest zip using your DB.
$look_zip = $db->getClosestZipMatch($number);
} else {
echo $number . " isn't 5 digits only, do something.";
}