Adding error to each form field that doesn't match validation with arrays

Hi all,

I’ve finally figured out how to work with arrays (in the way I want to for my current project), basic stuff probably but I’m patting myself on the back for these little accomplishments!

I have a form in which the user will be able to enter 10x numeric IDs and 10x alphanumeric Titles, grabbed with CarID[] and CarTitle[] as arrays.

What I want to do is, for each field that fails validation (say, is empty), I want to somehow link that element in the array back to the form field it was taken from and display an error.

So let’s say if the sixth CarID element has no value, place an error in that form field’s value (or add a error class to that input’s tag).

I know the index for the sixth CarID will be 5 (index starts at 0), but I don’t want to have to explicitly declare a variable or specify an index number for each input field.

It should just know which form field where the empty/invalid value came from and apply the error to that field.

[php]foreach (($CarID as $ID) && ($CarTitle as $Title)) {
if ((empty($ID)) || (empty($ID)) {
echo “This field is empty! Enter something or the form won’t submit!”;
}
}[/php]

Is it relatively straight forward?

Post all your code.

Thank you, the full code is:

[php]<?php
// clear variables that are referenced without form submission
$error = “”;

// connect to database, validate, save to database on form submission
if ($_SERVER[“REQUEST_METHOD”] == “POST”) {

// create connection (url, username, password, database name)
$con = mysqli_connect("","","",""); // details redacted

// check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$CarID = $_POST[‘CarID’];
$CarTitle = $_POST[‘CarTitle’];

// check if both arrays are empty
if ((!array_filter($CarID)) && (!array_filter($CarTitle))) {
echo ‘

All form fields empty!

’;
}
else {
echo ‘

Some form fields empty!

’;
}

// check if a value of an array is empty
foreach (($CarID as $ID) && ($CarTitle as $Title)) {
if ((empty($ID)) || (empty($Title))) {
$error = “class=“error””;
}
else { // echo user’s input
echo “

”.$ID." “.$Title.”

";
}
}

/* hidden as $sql not set and causes error / figure out way to only add values that pass validation and ignore others
$sql=“INSERT INTO ids_titles (CarID, CarTitle) VALUES (’$CarID1’, ‘$CarTitle1’), (’$CarID2’, ‘$CarTitle2’), (’$CarID3’, ‘$CarTitle3’), (’$CarID4’, ‘$CarTitle4’), (’$CarID5’, ‘$CarTitle5’), (’$CarID6’, ‘$CarTitle6’), (’$CarID7’, ‘$CarTitle7’), (’$CarID8’, ‘$CarTitle8’), (’$CarID9’, ‘$CarTitle9’), (’$CarID10’, ‘$CarTitle10’)”; */

/* hidden as $sql not set and causes error
if (!mysqli_query($con,$sql))
{
die('Error: ’ . mysqli_error($con));
}
*/
mysqli_close($con);
}
?>

input[type="text"] { height: 20px; }

input[name*=“CarID”] {
width: 65px;
}

input[name*=“CarTitle”] {
width: 450px;
}

form > div {
margin-bottom: 4px;
}

.error {
color: red;
font-style: italic;
}

input.error {
border: 2px solid red;
}

" method="post" name="myForm">
/> />
/> />
/> />
/> />
/> />
/> />
/> />
/> />
/> />
/> />
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { print_r($_POST); } ?> [/php]

Short on time at the moment. Check out the code example on my site that deals with form arrays. It should give you a clue to get going. You will want to do your error checks in the for loop right before the insert statement.

http://galaxyinternet.us/php-insert-form-array/

Thanks Kevin,

I’m not quite at that stage, I’m still grappling with validating my user’s input. I did look at your page and it looks very useful, I’m just trying to build my script from the ground up so will find a way to integrate your code soon.

So after sleeping on it (I find that helps when I’m starting to scream at my PC is frustration at my lack of knowledge), I’ve written down what I want to do and the code I’ve written so far (which, no surprise) isn’t working!

The plan:

[ol][li]Ignore a pair of CarID/CarTitle text inputs if they are both empty. So I validate only if one of those fields has a value…[/li]
[li]For each CarID that doesn’t have a value (but it’s adjacent CarTitle does), red outline the CarID adjacent to that CarTitle.[/li]
[li]For each CarTitle that doesn’t have a value (but it’s adjacent CarID does), red outline the CarTitle adjacent to that CarID.[/li]
[li]Assuming that the user has filled in both CarID and CarTitle (that are adjacent to each other), for each CarID that is not numeric, apply blue border to that form field.[/li]
[li]Assuming criteria above is passed, show success message (in lieu of me hitting the next part of this project to only add the values that have passed validation to the database).[/li][/ol]

Here’s the script:

[php].error {
border: 1px solid red;
}

.not_numeric {
border: 1px solid blue;
}

name="CarID[]" value="" maxlength="20" /> name="CarTitle[]" value="" maxlength="175" />

…plus 9x more…

$error = $success = “”;

// check if form field is empty
if ((!array_filter($CarID)) && (!array_filter($CarTitle))) {
echo “

All form fields empty!

”;
}
else {
foreach (array_combine($CarID, $CarTitle) as $ID => $Title) {
if ((!empty($ID)) && (empty($Title))) {
$error = “class=“error””;
}
elseif ((empty($ID)) && (!empty($Title))) {
$error = “class=“error””;
}
elseif (!is_numeric($ID)) {
$error = “class=“not_numeric””;
}
else {
$success = “

Form passed validation and submitted!

”;
}
}
}
[/php]

The result is:

[ol][li]If I enter a number into a CarID field, all the form fields get a blue border. Strange, because it’s a number! It should’ve only given the CarTitle form field next to it to a red border.[/li]
[li]The same thing happens if I enter text into a CarTitle field but don’t enter anything in the CarID fields.[/li]
[li]In my third test, I entered text into one of the CarID fields and all the form fields gained a red border.[/li][/ol]

In short, it seems that the validation is occurring on all the form fields at once and !is_numeric doesn’t appear to be working. I think it’s time for me to sleep again… arrrggghhhh!

Kevin is it possible to do what I want in PHP? Am I biting off more than I can chew at the beginning of learning PHP? Should I be doing this in a simpler way?

I’m slightly more confident with jQuery but I’d like to be as secure as possible, also I got a few other ideas for my work so I really need to know my way around PHP to make the magic happen!

Best thing I could tell you is learn to crawl before you try to walk. Start with the basics and move on from there. The only thing missing from the code example I showed you is the validation. Start with my working code and see if you can get validation to work with that then you can change the field names to what you want them to be.

Sponsor our Newsletter | Privacy Policy | Terms of Service