In order to troubleshoot my issue, I created a simple index.php file with 2 input fields and a button that redirects to page2.php.
These input tags have a regex pattern for Bootstrap-4 form validation.
Issue 1: The validation only occurs after clicking the button, not as I type in the inputs.
Issue 2: Upon refreshing without entering any data, the button still redirects me to page2.php.
I suspect that the problem lies with addEventListener('load')
, but being new to PHP, JS, Bootstrap, and life in general, I'm not entirely sure...
Any suggestion or idea would be greatly appreciated!
Here is the code snippet:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<style>
input[type="submit"]:disabled {
background-color: red;
}
</style>
</head>
<body>
<div class="container mt-2">
<div class="row">
<div class="col-md-4 offset-md-4">
<form action="page1.php" id="myForm1" class="was-validation" novalidate>
<div class="form-group">
<input type="text" class="form-control" pattern="^[a-z]{3,6}$" autofocus>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">a to z only (3 to 6 long)</div>
</div>
<div class="form-group">
<input type="text" class="form-control" pattern="^[a-z]{3,6}$" autofocus>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">a to z only (3 to 6 long)</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
(function() {
window.addEventListener('load', function() {
let currForm1 = document.getElementById('myForm1');
currForm1.addEventListener('submit', function(event) {
if (currForm1.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
currForm1.classList.add('was-validated');
}, false);
});
})();
</script>