I've five fields in the form
When a form is submitted and if three fields are not filled,it should validate and show errors on those three fields.
I used to do it using if loops,this will show one error at a time,instead, I want to show all the errors.
I want to check special characters,empty validation,min and max characters on each field.
preg_match('/^[a-z\d ]{3,20}$/i', $category
How to check them all at once using PHP?
Update
$errors = array();
$required = array("Name", "Email");
foreach($_POST as $key=>$value)
{
if(!empty($value))
{
$$key = $value;
}
else
{
if(in_array($key, $required))
{
array_push($errors, $key);
}
}
}
This can be used to check empty validation for all fiedls,how do i check for special characters,alpha numeric characters,the provblem would be each field will have different regex.
For eg: phone number and email can not have same regex.
Thanks in advance!
$errors = array();
if (preg_match('/^[a-z\d ]{3,20}$/i', $name)) {
$errors[] = "Please enter valid name.";
}
if (preg_match('/^[a-z\d ]{3,20}$/i', $category)) {
$errors[] = "Please enter valid category.";
}
if (preg_match('/^[a-z\d ]{3,20}$/i', $amount)) {
$errors[] = "Please enter valid amount.";
}
if(!empty($errors))
{
echo "The was an error filling out the form:<br><ul>";
foreach($errors as $msg)
{
echo "<li>$msg</li>";
}
echo "</ul>Please try again.";
}
Or, to make it more concise, use something like Ananth's answer.
// your 3 fields that need to be validated; Key is field, Value is error message if check invalid.
$validate = array("name" => "Please enter valid name.", "category" => "Please enter a real category.", "amount" => "Please enter an amount.");
$error = array();
foreach ($validate as $field => $message) {
if (preg_match('/^[a-z\d ]{3,20}$/i', $$field)) {
$error[] = $message;
}
}
if(!empty($errors))
{
echo "The was an error filling out the form:<br><ul>";
foreach($errors as $msg)
{
echo "<li>$msg</li>";
}
echo "</ul>Please try again.";
}
UPDATE
Seeing as how each check has it's on regex, the first example is easy enough to solve. As for the second example, it only requires a small change.
// your 3 fields that need to be validated;
// Key is Regex, value is array with the variable name (without the $) as the key,
// and the error message as the value.
$validate = array(
'/^[a-z\d ]{3,20}$/i' => array("name" => "Please enter valid name."),
'/^[a-z\d ]{3,20}$/i' => array("category" => "Please enter a real category."),
'/^[a-z\d ]{3,20}$/i' => array("amount" => "Please enter an amount.")
);
$error = array(); // Empty array to store errors in.
foreach ($validate as $regex => $data) { // Key = $regex, Value = array($variable, $error)
if (preg_match($regex, ${$data[0]})) { // This code is untested, so try it without the braces around $data[0]
$error[] = $data[1]; // If the data matches the regular expression provided, add the provided error message to the $error array.
}
}
if(!empty($errors)) // If the $errors array isn't empty (has an error in it)
{
echo "The was an error filling out the form:<br><ul>";
foreach($errors as $msg) // Goes through each error, printing it to an unordered list.
{
echo "<li>$msg</li>";
}
echo "</ul>Please try again.";
}
Note than in the above example, each has the same example regex, but it's simple enough to change those to your needs.
EDIT
All the code above is untested, though it should work, if it doesn't, try removing the braces around $data[0], as mentioned in the accompanying comments.
UPDATE 2
If you need to add an optional checker, the same code can be modified slightly, with an extra foreach loop, for all the optional fields to check.
// your 3 fields that need to be validated;
// Key is Regex, value is array with the variable name (without the $) as the key,
// and the error message as the value.
$required = array(
'/^[a-z\d ]{3,20}$/i' => array("name" => "Please enter valid name."),
'/^[a-z\d ]{3,20}$/i' => array("category" => "Please enter a real category."),
'/^[a-z\d ]{3,20}$/i' => array("amount" => "Please enter an amount.")
);
$optional = array(
'/^[a-z\d ]{3,20}$/i' => array("shipping" => "Please enter valid shipping location."),
'/^[a-z\d ]{3,20}$/i' => array("options" => "Please enter an clean option.")
);
$error = array(); // Empty array to store errors in.
foreach ($required as $regex => $data) { // Key = $regex, Value = array($variable, $error)
if (preg_match($regex, $$data[0])) { // This code is untested, so try it with or without the braces around $data[0]
$error[] = $data[1]; // If the data matches the regular expression provided, add the provided error message to the $error array.
}
}
foreach($optional as $regex => $data)
{
if(strlen(trim($$data[0])) > 0) // If the trimmed length of the string (all leading and trailing whitespace removed) == 0?
{
if (preg_match($regex, $$data[0])) { // This code is untested, so try it with or without the braces around $data[0]
$error[] = $data[1]; // If the data matches the regular expression provided, add the provided error message to the $error array.
}
}
if(!empty($errors)) // If the $errors array isn't empty (has an error in it)
{
echo "The was an error filling out the form:<br><ul>";
foreach($errors as $msg) // Goes through each error, printing it to an unordered list.
{
echo "<li>$msg</li>";
}
echo "</ul>Please try again.";
}
$validate = array("name", "category", "amount"); // your 3 fields that need to be validated
$error = '';
foreach ($validate as $field) {
if (preg_match('/^[a-z\d ]{3,20}$/i', $$field)) {
$error .= $field;
}
}
Later, based on $error you can show your errors.
Related
I need to include more then one error if i click on Submit button. if a user didn't filled all the required fields..error should be shown on top of my form
Currently when i Hit the submit button, The errors was pointing to the "Comment" line and Only the "Comment" errors was shown
I used - $error=$error."<br/> or $error.="<br /> none of them working as expected
How to display all my fields with and error message?
My Code has shown below
<?php
if ($_POST["submit"]) {
if($_POST['email']) {
$error="<br/>Please enter your Email address";
}
if($_POST['dest']) {
$error.="<br/>Please enter your Destination Name ";
}
if($_POST['dcity']) {
$error.="<br/>Please enter your Departure City ";
}
if($_POST['name']) {
$error.="<br/>Please enter your Name ";
}
if($_POST['cnum']) {
$error.="<br/>Please enter your Contact Number";
}
if($_POST['adults']) {
$error.="<br/>Please enter Number Of Adults";
}
if($_POST['child']) {
$error.="<br/>Please enter Number Of Children";
}
if($_POST['comment']) {
$error.="<br/>Please enter Your Comments ";
}
if ($error){
$result='<div class="alert alert-danger"><strong>There were error(s) in your form:</strong>' .$error.' </div>';
}
}
?>
First of all, you should check properly if the fields are empty, like so:
if(empty($_POST['email'])) {
Your code is actually doing the opposite, currently the condition is matched if the variable is true(-ish). In any case, to save yourself from warnings, use empty() or !empty() -- in case of POST data; otherwise also isset() etc. -- rather than directly testing a variable that may or may not exist.
Second, you should either: Use an array for pooling up your errors: $error = []; ... $error[] = 'This error'; -- Or: first define an empty string, $error = '';before trying to concatenate with .= to it. As it stands, your code only defines the error variable if the email field is unset. Using an array will spare you from the <br /> concatenation hassle as well; just implode('<br />', $error).
Edit: If you want to get rid of all that repetitive checking and redundant code, and make it easier to extend your app in the future, you could abstract things a bit and do something like this:
$err_msgs = [
'email' => 'your Email address',
'dest' => 'your Destination Name',
'dcity' => 'your Departure City',
'name' => 'your Name',
'cnum' => 'your Contact Number',
'adults' => 'Number Of Adults',
'child' => 'Number Of Children',
'comment' => 'your Comments',
];
$errors = [];
foreach($err_msgs as $key => $msg) {
if (empty($_POST[$key])) {
$errors[] = 'Please enter ' . $msg;
}
}
if (count($errors) > 0) { // OR: if (!empty($errors)) {
$result = '<div class="alert alert-danger"><strong>
There were error(s) in your form:</strong><br />'
. implode('<br />', $errors)
. ' </div>';
}
What's happening here: We define all expected fields and their unique error messages in an array as key/message pairs, the keys being identical to your form fields' names. Then we loop over the array and check for empty fields, and generate all error messages in one place, adding them into an array. Finally, if the $errors array has messages, we print them out.
Best solution:
Assign an empty string: $error = '';
then you will concatenate it. I.e.
if($_POST['some_key']){
$error .= 'this is an error';
}
//...
if($error != '') {
echo $error;
}
I think the issues you met due to a case:
if email exist so what $error to concatenate after that.
But as usual, we validate those like this:
if(isset($_POST['some_key']) && empty(trim($_POST['some_key']) {
//put error string here
}
I am trying to create a form where if a user doesn't enter information into a specific input then on submission of the form, the user is alerted to fill in that input field only (e.g. "Please enter a username").
Currently I have a foreach loop that loops through each input field of the form and assigns a variable with the same name as the field (i.e. $name = $_POST['name']).
What would I implement in my code so I could check each individual input field is empty or not and tell the user this, but keep the code to a bare minimal?
foreach ($_POST as $key => $value) {
$$key = $_POST[$key]; //assigns variable to input.
}
if(!empty($$key)) {
//code if all fields are not empty
}
else {
echo "Please fill in all fields";
}
While I do not agree with how you are doing this, a solution would be to add an error array to your first foreach loop.
foreach ($_POST as $key => $value) {
${$key} = $_POST[$key];
// If the field is empty, set an error
if( empty($value) ) {
$errors[] = 'Please enter a ' . $key . '.';
}
}
And then change the bottom to check for the error array. If it's empty, run your code to complete the form submission. If not, loop through the errors.
if( empty($errors) ) {
//code if all fields are not empty
}
else {
// Loop through each error found
foreach($errors as $error) {
echo $error;
}
}
I've a form,in the form only few fields are mandatory.When a fields is not mandatory,it should not check for empty data validation.If the non mandatory field contain data then it shoudl check the data,validation should happen only when data present.
My below code check for all fields.For eg:Say phone is not mandatory in below code,how to change the code.
$validate = array(
array($x, '/^[a-z\d ]{4,20}$/i', "Please enter valid name."),
array($y, '/^[a-z\d ]{4,20}$/i', "Please enter a real category."),
array($phone, '/^\(?[0-9]{3}\)?|[0-9]{3}[-. ]? [0-9]{3}[-. ]?[0-9]{4}$/' , "Please enter a valid phone number")
);
$error = '';
foreach ($validate as $validation)
{
if (!preg_match($validation[1],$validation[0]))
{
$error .= $validation[2];
}
}
if($error != '')
{
echo $error;
exit;
}
Comment on this post,if it is not clear.
Thanks in advance!
If you want to check if at least required fields have been submitted, you can check whether they have been set and have a truthy value using the isset and empty functions.
For example:
if ( isset($_POST['username'], $_POST['password']) &&
! empty($_POST['username']) && ! empty($_POST['password']) ) {
// validation here
}
That would check if the username and password fields were submitted and have a value, whereas for example an email field wouldn't necessarily have been filled in for the above condition to return true.
If you know the mandatory fields before hand I'll suggest you group them in an array and test for based on the current key. If a key is in not mandatory but holds value you can test otherwise do your regular check.
$error = '';
$mandatoryFields = array('key1', 'key2' 'key3');
foreach ($validate as $validation)
{
if (!in_array($validation[0], $mandatoryFields) && strlen(trim($validation[0])) > 0)
{
// There is data in a non mandatory field.
// Perform your test.
}
else {
// Do your regular test.
if (!preg_match($validation[1],$validation[0]))
{
$error .= $validation[2];
}
}
}
You can give this a try.
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!
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;
}
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;
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
More concise way to check to see if an array contains only numbers (integers)
PHP checking if empty fields
I have form that submits 10 fields, and 7 of them should be filled, here is how i chek it now in PHP:
if (!$name || !$phone || !$email || !$mobile || !$email || !$state || !$street || ! $city) {
echo '<div class="empty_p">You have empty fields!!!</div>';}
else{
//process order or do something
}
My question is: is there more simple way to do this? Because sometimes I have even more strings to check (12-15)
Another possibility:
$elements = array($name, $email, $mobile);
$valid = true;
foreach ($elements as $element) {
if (empty($element)) {
$valid = false;
}
}
if ($valid) {
// complete
} else {
// alert! some element is empty
}
Something like this?
foreach($_POST as $key => $value)
{
if (empty($_POST[$key]))
{
echo '<div class="empty_p">'.$_POST[$key].' is empty.</div>';
}
}
It's good to be specific about where this data should be expected, e.g. $_POST:
if (!isset($_POST['name'], $_POST['phone'], $_POST['email'], $_POST['mobile'], $_POST['state'], $_POST['street'], $_POST['city'])) {
// something is up
}
You can shorten this code a little bit by creating an array with your required field names:
$required_fields = array('name', 'phone', 'email', 'mobile', 'state', 'street', 'city');
The 'check-for-existence' code can then be simplified to:
foreach ($required_fields as $f) {
if (!isset($_POST[$f])) {
// something is up
}
}
The better way ™
However, you should seriously consider combining both existence and validation / sanitization checks. PHP provides a family of filter functions functions that you can use to validate and/or sanitize your input variables. For example, to get equivalent behavior as above:
$required_fields = filter_input_array(INPUT_POST, array(
'name' => FILTER_UNSAFE_RAW,
'email' => FILTER_VALIDATE_EMAIL,
));
if (is_null($required_fields) || in_array(null, $required_fields, true)) {
// some fields are missing
}
Fields that exist but fail validation will be set to false, so this is how you detect such an event:
foreach ($required_fields as $name => $value) {
if (false === $value) {
// field $name failed validation (e.g. bad email format)
} elseif (!strlen(trim($value))) {
// field is empty
}
}
The best way would be to create some sort of form validator. However you can use this function:
<?php
function isAnyEmpty() {
$total = 0;
$args = func_get_args();
foreach($args as $arg)
{
if(empty($arg)) {
return true;
}
}
return false;
}
$var1 = 1;
$var2 = 'test';
$var3 = '';
if(isAnyEmpty($var1, $var2, $var3)) {
echo 'empty fields!';
}
?>
You could try creating a general validation class that could be reused and be more precise.
Some pseudo code:
<?
class validateFields {
$validators = array(
"name" => array(
"empty" => array(
"rule" => "some regex",
"errorMessage" => "name may not be empty"
),
"noNumbers" => array(
"rule" => "some regex",
"errorMessage" => "No numbers are allowed in the name field"
)
),
"otherVariable" => array(
"atLeast50chars" => array(
"rule" => "some regex",
"errorMessage" => "This field must be at least 50 chars"
)
)
);
public function Validate($post){
$errors = array();
foreach($_POST as $key => $value){
if(!array_key_exists($key, $validators)) {
continue;
}
foreach($validators[$key] as $validator) {
if(!preg_match($validator["rule"], $value) {
$errors[$key] = $validator["errorMessage"];
break;
}
}
}
return $errors;
}
}
?>
Then in your code you could do something like:
$errors = Validate($_POST);
foreach($error as $errorMessage) {
echo $errorMessage . "</br>";
}
Of course you could fancy this up, adding divs with classes right below/beside the concerning input field and load the $errorMessage into there.
I'm sure there's loads of examples out there :)
You can write Foreach loop
foreach($_POST as $key => $value)
{
if (!isset($_POST[$key]) || empty($_POST[$key])
{
echo '<div class="something">You have empty fields!!!</div>';
}
}
<input type="text" name="required[first_name]" />
<input type="text" name="required[last_name]" />
...
$required = $_POST['required'];
foreach ($required as $req) {
$req = trim($req);
if (empty($req))
echo 'gotcha!';
}
/* update */
OK! guys, easy...
You can make it more secure, just with type casting as all we programmers do for out coming data, like $id = (int) $_GET['id'], like $username = (string) addslashes($_POST['username']) and so on...;
$required = (array) $_POST['required'];
And then, what ever comes from post fields let them come, this code just seek what it need.
That is it! Uhh...