I have one PHP file that takes data then displays it using the $_POST method. I know how to validate the inputs of the form using PHP:
if($data = "") {
echo "This Field Is Required";
}
But I don't know how to avoid the form submitting the data. Do I add a new line to this if statement? I saw something to do with header:locations in this post - Stop Submit With Empty Input Values Using PHP, but I do not think this will work for me because my form and processor are in a single file. I am sure this is simple, but it is extremely difficult to find any answer when browsing the web. Thanks for any help :)
This is a front-end (client side validation), you need to validate the form at your PHP (server side) too. But using html5 and js you can prevent form submit if it is not validated.
For php you need to validate at server side. If not valid you don't save to the database and you should not redirect the user. Return some error messages ask for more data/ required fields.
example:
$error = [];
if ($offer['year'] < 2014) {
$error['year'] = 'must be later than 2014';
}
...
if (count($error)) {
echo "your error msg here"
} else {
$db->insert('formtable', $form);
}
$(document).ready(function() {
// loader (after submit)
$('button[type="submit"]').click(function(e) {
let formValidity = $('#myform')[0].checkValidity();
if (formValidity) {
console.log('Submitted yep!');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
<input type="text" value="" required>
<button type="submit" value="submit">SUBMIT</button>
</form>
<div id="other">
Trigger the handler
</div>