my registration form has basic validation for html attributes, e.g. type = ’email’ etc. They display nicely styled by the new feature in Bootstrap Validation.
The problem occurs when I send the form to PHP. First, the data goes through AJAX to PHP to display errors without refreshing the page, but when checking e.g. if the entered email is already registered with a negative result, my input is still marked as: valid (green highlight). What should I do
register.php
$success = false; $error = false; $mssg = "Error"; if(!isset($_POST['email']) && !isset($_POST['pass'])){ $mssg = "Inputs are empty"; }else{ //example result for database $used_email = "foo@email.com"; // example validation if($_POST['email'] == $used_email){ $error = 'email'; $mssg = "Email is already taken!"; }else $success=true; } header('Content-Type: application/json'); echo json_encode(array('success' => $success, 'error'=> $error, 'mssg' => $mssg)); exit;
(function (){ $("#formregister").on('submit', function(ev){ const form = $(this); ev.preventDefault(); ev.stopPropagation(); var obj= new Object; Object.keys(form[0].getElementsByTagName('input')).filter(function(key) { obj[form[0][key].id] = form[0][key].value; }); if (this.checkValidity()) { $.ajax({ type: "POST", url: "register.php", data: obj, cache: false, success: function(data) { if(!data.success) { if(data.error){ $("#"+data.error).addClass("is-invalid").focus(); $("#"+data.error).next().html(data.mssg); }else $("#result").attr("class", "alert alert-danger").html(data.mssg); }else{ $("#result").html("Success"); $("#result").attr("class", "alert alert-success"); } } }); }else form.find(":invalid").first().focus(); form.addClass("was-validated"); }); })();
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> <form class="needs-validation" id="formregister" novalidate> <div id="result"></div> <div class="mt-2"> <label for="email" class="form-label">E-mail</label> <input type="email" class="form-control" id="email" required> <div class="invalid-feedback">123</div> </div> <div class="mt-2"> <label for="pass" class="form-label">Password</label> <input type="password" class="form-control" id="pass" required> <div class="invalid-feedback"></div> </div> <div class="col-12 justify-content-end d-flex mt-4 mb-2"> <button type="submit" class="btn btn-primary">Register</button> </div> </form> </div>
If I add .is-invalid class during validation, input doesn’t change its style to red.
Advertisement
Answer
I found the solution! The :invalid and :valid attributes have style advantages over classes, so the .is-invalid class must have border attributes with !imporant at the end.
For people who will have a similar problem in the future.
Need to add to boostrap.css .is-invalid and .is-valid -> !important