I'm trying to validate the fields in a form using PHP, but I need something similar to e.preventDefault() to stop the page from refreshing/loading if there are errors in the validation. I'm not very familiar with JavaScript/jQuery, so I'd prefer to handle all of the POST data with PHP (if possible). I was trying to run the checkForm() function on submit, but I realized it was always returning true since it runs before the data gets posted. I also thought about creating a JS function to call e.preventDefault(), but I think my only option would be a (#form).submit() function and I want to avoid having to retrieve and post data in JS/jQuery because some elements are DOM elements and I'm not sure how to access them in JS/jQuery.
To give you an idea of the DOM elements I'm working with, here's a jsfiddle that creates rows dynamically:
https://jsfiddle.net/hnj6ed1y/52/
There could be multiple rows and the fields have similar names (ie: textfield1, textfield2, etc.).
Any ideas? Thank you in advance for all of your help!
<?php
// setting initial variables here
?>
<script>
var isDateTimeValid = true;
function checkDates(val) {
if (val == false) {
isDateTimeValid = false;
}
else {
isDateTimeValid = true;
}
}
function checkForm () {
if (isDateTimeValid == true) {
return true;
}
else {
alert("Please check date/times");
return false;
}
}
</script>
<?php
if(isset($_POST['next'])){
// Validating POST data here
$dateValid = convertOORDateTime($date1, $time1, $date2, $time2);
if ($dateValid < 1) {
echo "<script> checkDates(false); </script>";
$errors[] = 'Please make sure your dates are correct';
}
else {
echo "<script> checkDates(true); </script>";
}
}
$err_msg = '';
if(!empty($errors)){
// want to stop page refresh/load here
$err_msg = '<p class="error">'.implode('<br />', $errors).'</p>';
}
?>
<!DOCTYPE html>
<form name="form1" id="form1" method="post" action="<?php print $thispage;?>" onsubmit="return checkForm()">
<?php echo $err_msg; ?>
</form>