Add A Class To An Input Using PHP

Viewed 1742

I have been working on a form that uses PHP form validation. I also have a class in my CSS file that should be added to each of the invalid inputs. You can view a JSFiddle here. The class I am trying to add is only visible when the input is returned invalid. The class name is .invalid which you can find in the CSS. Thanks in advance, and any help is appreciated.

2 Answers

You can have PHP add a class to your inputs if a field is invalid, but you may need to adjust your approach.

If you want to maintain using a form POST method (as you have it), you'd want to move your validation code to be processed on the same page that renders your view (the easiest way to do this is to have it within the same page). You can still use and include a separate file to pull in a PHP class or other system you want to use for validation if you want to keep your code neat. Here's an example:

<?php
// filter_input returns null or false if invalid.
$firstname = filter_input(INPUT_POST, 'firstname', FILTER_SANITIZE_STRING);
?>

<form method="POST" action="<?php echo getenv('REQUEST_URI'); ?>">
<input type="text" name="firstname" value="<?php echo $firstname; ?>" class="<?php echo $firstname ? '' : 'invalid'; ?>" />
<input type="submit" name="submit" value="Submit" />
</form>

However, I would recommend a more robust approach which would be to use an AJAX handler for submitting your form. This will give your users a better experience, and it also allows you to neatly have your form processing entirely separate from your view. That solution is a bit beyond the scope of this question, but ultimately you would have your PHP AJAX handler return information as to whether or not the submission was valid or what fields are invalid and have the javascript add your invalid class to the fields in error.

Let's assume there are two inputs and as you want to validate via PHP the validation process will be after submitting the form as

HTML

<input type="text" title="First Name" aria-placeholder="First Name" id="name" required />
<input type="text" title="Last Name" aria-placeholder="Last Name" id="name" required />

PHP

for($i = 0;$i < sizeof($_POST);$i++){
if($_POST[$i] == null || $POST[$i] == ""){
echo "Please insert :".$_POST[$i];
 }
}

Note: PHP will validate the form after the form has been submitted for the validation before the submission you will need use javascript.

Related