Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
My problem is that i have a form which i made in HTML which contains 5 fields which are always required (name, city, adres, house number and phone number)
Then I have 11 fields where only 1 field is required.
My question is specific to those 11 fields only.
So basically when the user submits the form (first 5 are filled in properly) it needs to give some kind of error.
But when 1 or more of those 11 input fields are filled in it needs to go through.
I tried countless of different things. And i just read something about placing those 11 input fields in a class="" and make a custom validator of some kind.
I don't know if this is the correct solution (and if it is what does a custom validator look like)
I'm not experienced in php or JQ or JS that's why this is such a big problem for me.
I hope my question is formulated correctly, if not let me know!
If I'm understanding you correctly, you have 11 fields and at least one of them must be filled.
This will require some custom validation, yes.
First, I would suggest having the fields like this:
<input type="text" name="options[]" />
The name can be whatever you want, but the important thing is those square brackets. They define input as an array, so with 11 inputs you'll have 11 items. If you need to tell them apart, try:
<input type="text" name="options[something]" />
Now, the server-side validation. This is the most important part - JS validation is secondary.
To validate this field in PHP, do this:
$completedFields = array_filter($_POST['options']);
if( !$completedFields) die("You did not fill in any of the 11 inputs!");
Simple!
And finally, some JS validation. Presumably you have some kind of submit handler, but if not have your form like this:
<form action="..." method="post" onSubmit="return validationFunction(this);">
Now your JS can be like this:
function validationFunction(form) {
// if you're using name="options[]":
var options = form['options[]'];
// if you're using named options like options[something]
var options = (function() {
var elms = form.elements, l = elms.length, i, ret = [];
for( i=0; i<l; i++) {
if( elms[i].name.match(/^options\[.*\]$/)) ret.push(elms[i]);
}
return elms;
})();
// then do this:
var l = options.length, i;
for( i=0; i<l; i++) {
if( options[i].value != "") return true;
}
alert("Please fill out at least one of the options.");
return false;
}
Hope this helps!
For a server-side validation, use a quick count check
$completedFields = 0;
if (!empty($_POST['fieldName1'])) $completedFields++;
if (!empty($_POST['fieldName2'])) $completedFields++;
// and so on...
if ($completedFields > 0) {
// validated
} else {
// error
}
You could also use a POST array depending on how the fields are conventionally named and then foreach through each check in a similar manner
HTML:
Field 1 <input type="text" name="extra_field[]" value="" /><br />
Field 2 <input type="text" name="extra_field[]" value="" /><br />
Field 3 <input type="text" name="extra_field[]" value="" /><br />
...
Field 11 <input type="text" name="extra_field[]" value="" /><br />
Then in PHP:
<?php
$valid = FALSE;
$extra_fields = isset($_POST['extra_field']) ? $_POST['extra_field'] : array();
foreach ($extra_fields as $field) {
if (!empty($field)) {
$valid = TRUE;
break;
}
}
if ($valid == FALSE) {
echo 'Ooops, you must complete at least one of the 11 fields';
}
?>
if (!empty($_POST['field1'])OR !empty($_POST['field2']) OR !empty($_POST['field3'] ))
{
// SUBMIT FORM
} else {
// display error message
}
This is for 3 fields , you can extend it to 11. Hope this helps.
Related
I have a simple PHP form that I'd like to improve validation to help fight empty form submissions from bots.
I have the following array that houses input names from another page.
$expected = array('Project-Inquiry','Name','Company-Name','Phone-Number','Email');
I'd like to verify that these elements, in fact, do contain content, as they're already verified with JS on the previous page. JS is only good when it's enabled, so I'd like to add an extra layer of validation here for when it's disabled.
I tried the following:
$expected = array_filter($expected);
if (!empty($expected)) {
// Do Something
}
And I have also tried the following:
$error = false;
foreach($expected as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error) {
// Do Something
}
I seem to be falling short. Any suggestions?
If you want to fight against bots
Create a hidden input that human doesn't see and bots will fill it. You need to check that input before doing anything. If that input filled, it means that form sent by bot not human.
Create a session with current time when you are showing form, when post happening check the time difference. if it is less than 3 sec it's a bot.
use captcha system.
If you want to validate inputs
Don't do validation like what you did on your question. You should try to validate each one of them with proper validation method. for example how you should validate email is completely different from name.
for example do this for email:
$email = (isset($_POST['email']) && is_string($_POST['email']))? trim($_POST['email']) : '';
$email_error = (filter_var($email,FILTER_VALIDATE_EMAIL))? true : false;
for name is different:
$name = (isset($_POST['name']) && is_string($_POST['name']))? trim($_POST['name']) : '';
$name_error = (strlen($name)>20 || strlen($name)<3)? true : false;
You can add more filter to my examples.
Have you considered about using a library to validate?
I recommend you to use https://laravel.com/docs/5.5/validation, so you can validate more complex rules also, and it is very clear.
Let your expected data be array be
$expected = ['name', 'email', 'mobile'];
let form post values be $_POST
foreach($_POST as $key => $value) {
if (empty($value) && in_array($key, $expected)) {
if ($value=='') {
echo $key. ' is should not be empty'."<br/>";
}
}
}
you can get result as expected
HTML FORM
<form action="" method="post">
Name <input type="text" name="name"><br>
email <input type="text" name="email"><br>
mobile<input type="text" name="mobile">
<input type="submit" value="Submit">
</form>
I've got a dilema, I've got my database created, my input form works, however I'm looking to add validation to the POST so that certain things cant be entered, I can release snippets of code if needed however I can't find what I'm looking for.
My form basically
<input type="text" name="id1" placeholder="Pick a number">
<input type="text" name="id2" placeholder="Pick another number">
However, I would like to display an error if they pick the same number
EG: IF ID1 == ID2 then ECHO error.
However I'm unsure of the code, I have a simple PHP Mysql form.
You can use this code:
if($_POST['id1'] == $_POST['id2']) {
echo 'error';
}
on the action of your form i.e you define in your action attribute of form action='somepage.php write below code.
if(isset($_REQUEST['id1']) && isset($_REQUEST['id2'])){
if($_REQUEST['id1'] >= $_REQUEST['id2']){
echo "error";
}
}
To be sure, use typecasting plus check if posts are set.. e.g.
<?php
$id1 = isset($_POST['id1']) ? (int) $_POST['id1'] : 0;
$id2 = isset($_POST['id2']) ? (int) $_POST['id2'] : 0;
if(!empty($id1) && !empty($id2) && $id1 !== $id){
// success
} else {
// fail
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a special form I have been making that uses some cusotm post types in wordpress. At one point I need to echo a variable $i into an if statement.
There is some validation stuff at the top that will look like this and the code in the loop is below. Pretty much I have been trying to get the majorCause1Error to be majorCause $i Error if you know what I mean, so all up it will be like 1-13
Edit: Sorry If it is hard to see what I am asking, I am finding it really hard to word my problem.
So there is a loop running around the li tags and it echos $i into the name etc so it becomes majorCause1 then next one majorCause2 and the next one magjorCause3 etc etc
Under the labels there is an if statement that is like - if($majorCause1Error !='') { do something } - I want this to be like if($majorCause1Error !=''){} and then the next one be like if($majorCause2Error !=''){} and then if($majorCause3Error !=''){}
Does this make more sense?
Here is a link to the site http://www.foresightaus.com.au/form/
if(trim($_POST['majorCause1']) === '') {
$majorCause1Error = "Please enter a major cause.";
$hasError = true;
} else {
$majorCause1 = trim($_POST['majorCause1']);
}
if(trim($_POST['majorCause2']) === '') {
$majorCause2Error = "Please enter a major cause.";
$hasError = true;
} else {
$majorCause2 = trim($_POST['majorCause2']);
}
<li class="fill-in">
<label for="majorCause<?php echo($i); ?>"><?php echo($j); ?>. State one major cause:</label>
<input type="text" name="majorCause<?php echo($i); ?>" id="majorCause<?php echo($i); ?>" value=""/>
<?php if($majorCause1Error != '') { ?>
<span class="error"><?=$majorCause1Error;?></span>
<?php } ?>
</li>
You probably want to be using an array but what you are referencing is called a variable variable and is supported by PHP!
Something like this should do it
${"majorCause{$i}Error"}
I have a form which (on a previous page) users can select how many items they want to include. Once the second page is submitted, it is run through a validation script which takes the requirement, the field name, and a message to return if an error occurs in the validation.
if($numFieldSelectedearlier > 0) {
for($z=1; $z<=$numFieldSelectedearlier; $z++) {
$rules[] = "required,name,Name for item {$z} is required.";
}
}
In my html form, the field looks like the following:
<form name="someForm" action="" method="post">
<?php if ($numFieldSelectedearlier > 0) {
for($y=1; $y <= $numFieldSelectedearlier; $y++) { ?>
<input type="text" name="name[]" id="name<?php echo $y; ?>" />
<?php }
} ?>
....
The problem I have is, the script is currently build to handle single elements (one field named "name", etc). The php validator takes all POST elements and breaks them out as fields to do the validation and I'm struggling to figure out how to either modify the validation script itself (which I'm somewhat hesitant to do given it would change the overall structure of the validator to check if the element name was itself an array then loop through) or if I am perhaps not thinking about a simpler way to handle the actual $rules creation piece.
Note: it may seem the only thing I care about is the a field is required but I want to essentially pass the arrayed item through the same validation options as any other field (required, numbers only, email, etc) so I don't want to duplicate code for what in theory already exists.
Thank you for any assistance you can provide.
Since you're doing a loop already on both sides, why not just use names like name1, name2, etc. and link your rules to those fields?
On the HTML side, you would change the name:
<input type="text" name="name<?php echo $y; ?>" ... />
And on the rules creation side, you would bind to those field names:
if($numFieldSelectedearlier > 0) {
for($z=1; $z<=$numFieldSelectedearlier; $z++) {
$rules[] = "required,name{$z},Name for item {$z} is required.";
}
}
This is more of a technique question rather than maybe code. I am having a php form with many fields (items to select). Naturally some of the items might be selected and some not. How do I know which ones are selected when i post the data from page 1 to page 2? I thought of testing each one if empty or not, but there are just too many fields and it doesn't feel at all efficient to use or code.
Thanks,
UPDATE EDIT:
I've tried the following and maybe it will get me somewhere before I carry on testing the repliers solutions...
<html>
<body>
<form name="test" id="name" action="testprocess.php" method="POST">
<input type="text" name="choices[shirt]">
<input type="text" name="choices[pants]">
<input type="text" name="choices[tie]">
<input type="text" name="choices[socks]">
<input type="submit" value="submit data" />
</form>
</body>
</html>
and then second page:
<?php
$names = $_POST['choices'];
echo "Names are: <br>";
print_r($names);
?>
This gives out the following:
Names are: Array ( [shirt] => sdjalskdjlk [pants] => lkjlkjlk [tie]
=> jlk [socks] => lkjlkjl )
Now what I am going to try to do is iterate over the array, and since the values in my case are numbers, I will just check which of the fields are > 0 given the default is 0. I hope this works...if not then I will let you know :)
I think what you're looking for is this:
<form action="submit.php" method="POST">
<input type="checkbox" name="checkboxes[]" value="this" /> This
<input type="checkbox" name="checkboxes[]" value="might" /> might
<input type="checkbox" name="checkboxes[]" value="work" /> work
<input type="submit" />
</form>
And then in submit.php, you simply write:
<?php
foreach($_POST['checkboxes'] as $value) {
echo "{$value} was checked!";
}
?>
The square brackets in the name of the checkbox elements tell PHP to put all elements with this name into the same array, in this case $_POST['checkboxes'], though you could call the checkboxes anything you like, of course.
You should post your code so we would better understand what you want to do.
But from what I understood you are making a form with check boxes. If you want to see if the check boxes are selected, you can go like this:
if(!$_POST['checkbox1'] && !$_POST['checkbox2'] && !$_POST['checkbox3'])
This looks if all the three check boxes are empty.
Just an idea:
Create a hidden input field within your form with no value. Whenever any of the forms fields is filled/selected, you add the name attribute of that field in this hidden field (Field names are saved with a comma separator).
On doing a POST, you can read this variable and only those fields present in this have been selected/filled in the form.
Hope this helps.
Try this.....
<?php
function checkvalue($val) {
if($val != "") return true;
else return false;
}
if(isset($_POST['submit'])) {
$values = array_filter(($_POST), "checkvalue");
$set_values = array_keys($values);
}
?>
In this manner you can get all the values that has been set in an array..
I'm not exactly sure to understand your intention. I assume that you have multiple form fields you'd like to part into different Web pages (e.g. a typical survey form).
If this is the case use sessions to store the different data of your forms until the "final submit button" (e.g. on the last page) has been pressed.
How do I know which ones are selected when i post the data from page 1 to page 2?
is a different question from how to avoid a large POST to PHP.
Assuming this is a table of data...
Just update everything regardless (if you've got the primary / unique keys set correctly)
Use Ajax to update individual rows as they are changed at the front end
Use Javascript to set a flag within each row when the data in that row is modified
Or store a representation of the existing data for each row as a hidden field for the row, on submission e.g.
print "<form....><table>\n";
foreach ($row as $id=>$r) {
print "<tr><td><input type='hidden' name='prev[$id]' value='"
. md5(serialize($r)) . "'>...
}
...at the receiving end...
foreach ($_POST['prev'] as $id=>$prev) {
$sent_back=array( /* the field values in the row */ );
if (md5(serialize($sent_back)) != $prev) {
// data has changed
update_record($id, $sent_back);
}
}