1

When a user submit forms,i'm checking empty validation and data validation.

For ex:In data ,first field is name,i'll check whether user has entered any other characters else than alpha character's.if he has entered then will show him an error message.Name should contain minimum of 4 characters and max of 20 characters

I'm using this code but it is not working correctly.How to check the regex.

$validate = array("Category"=>"$productCategory", "Name" => "$productName");

$error = '';

foreach ($validate as $key => $field) {

    if (preg_match('/^[a-z\d ]{4,20}$/i', $$field)) {
       echo $error .= $field;
    }
}

Thanks in advance!

5
  • please provide input, output, expected output. Commented Jun 19, 2012 at 7:34
  • Are accented characters, or other Unicode characters, allowed in names? Commented Jun 19, 2012 at 7:37
  • plus you have $$field instead of $field Commented Jun 19, 2012 at 7:37
  • 1
    I find this line echo $error .= $field; pretty strange. Can anyone explain it's logic? Commented Jun 19, 2012 at 7:42
  • @Andrius Naruševičius : none, we all missed it :) Updated my answer to show a correct way to use $error in this context. Commented Jun 19, 2012 at 7:51

2 Answers 2

3

You have a typo in the preg_match, you type $$field (2x$) instead of $field, your regex is fine it will match:

 - a character between a - z (case insensitive)
or
 - a digit between 0 - 9
or 
 - a "space" character.

Update code to answer @Andrius Naruševičius comment

$validate = array("Category" => $productCategory, "Name" => $productName);
$error = '';
foreach ($validate as $key => $field)
{
    if (preg_match('/^[a-z\d ]{4,20}$/i',$field))
    {
       $error.= $field;
    }
}

if($error)
{
    echo $error;
    exit;
}
Sign up to request clarification or add additional context in comments.

4 Comments

:a valid name can have spaces a-z,A-z & 0-9.
:Where to add error messages.Say,i've 10 regex and 10 feild,how do i use this in this logic.When form submitted,if 5 error all should be showed to user.
@user1415759 Removed \w and added a-z in the regex (\w allows a what you need + the underscore character). Second, it will print all 5 errors and exit the code, you don't whant to continue execution after an error occured ...
:I wrote an update,check you check my code.How do i validate empty field.
2

Do you mean:

$validate = array("Category"=>$productCategory, "Name" => $productName);

foreach ($validate as $key => $field) {

    if (preg_match('/^[\w\d]{4,20}$/i',$field)) {
       echo $error .= $field;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.