Bootstrap注册页:jQuery+BootstrapValidator验证、模态框触发及年龄校验需求
Hey there! Let's fix up your form to meet both requirements: showing a success modal after valid submission and adding age validation for the date of birth field (14-50 years old). Here's how to do it:
1. Add Age Validation Rule
We'll use BootstrapValidator's callback validator to calculate the user's age from their birth date and check if it falls within the 14-50 range. This validator lets us run custom logic to validate the field. Here's the key code snippet for this:
dob: { validators: { notEmpty: { message: 'The date is required' }, date: { format: 'MM/DD/YYYY', message: 'The date is not valid' }, callback: { message: 'Your age must be between 14 and 50 years old', callback: function(value, validator) { // Calculate age accurately (accounts for unpassed birthdays this year) const birthDate = new Date(value); const today = new Date(); let age = today.getFullYear() - birthDate.getFullYear(); const monthDiff = today.getMonth() - birthDate.getMonth(); // Adjust age if birthday hasn't occurred yet this year if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) { age--; } // Return true only if age is in the valid range return age >= 14 && age <= 50; } } } }
2. Fix Success Modal Trigger
Your existing onSuccess handler was missing a critical step: preventing the default form submission. Without this, the page would refresh immediately after validation, making the modal flash and disappear. Add e.preventDefault() to stop the default behavior:
onSuccess: function(e, data) { // Stop form from submitting (so modal stays visible) e.preventDefault(); // Show the success modal $('.modalMy').modal('show'); }
Full Working Code
I've also filled in missing HTML structure (like proper form wrapping, modal container) that was incomplete in your original code. Here's the complete, functional version:
<!DOCTYPE html> <html> <head> <!-- Required CSS Libraries --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-validator/0.5.3/css/bootstrapValidator.min.css"> </head> <body> <div class="container"> <h2>Bootstrap Form Validation</h2> <form id="validateform" class="form-horizontal"> <!-- Full Name Field --> <div class="form-group"> <label class="control-label col-sm-2" for="full_name">Full Name:</label> <div class="col-sm-10"> <input type="text" class="form-control" id="full_name" name="full_name" placeholder="Enter full name"> </div> </div> <!-- Password Field --> <div class="form-group"> <label class="control-label col-sm-2" for="password">Password:</label> <div class="col-sm-10"> <input type="password" class="form-control" id="password" name="password" placeholder="Enter password"> </div> </div> <!-- Confirm Password Field --> <div class="form-group"> <label class="control-label col-sm-2" for="confirmPassword">Confirm Password:</label> <div class="col-sm-10"> <input type="password" class="form-control" id="confirmPassword" name="confirmPassword" placeholder="Confirm password"> </div> </div> <!-- Email Field --> <div class="form-group"> <label class="control-label col-sm-2" for="email">E-mail:</label> <div class="col-sm-10"> <input type="email" class="form-control" id="email" name="email" placeholder="Enter email"> </div> </div> <!-- Date of Birth Field --> <div class="form-group"> <label class="control-label col-sm-2" for="dateOfBirth">Date of Birth:</label> <div class="col-sm-10"> <input type="text" class="form-control" id="dateOfBirth" name="dob" placeholder="MM/DD/YYYY"> </div> </div> <!-- Submit Button --> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Submit</button> </div> </div> </form> <!-- Success Modal --> <div class="modal fade modalMy" id="successModal" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h4 class="modal-title">Success</h4> </div> <div class="modal-body"> <p>Your form has been submitted successfully!</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> <!-- Required JS Libraries --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-validator/0.5.3/js/bootstrapValidator.min.js"></script> <script> $(document).ready(function() { // Initialize Datepicker $('#dateOfBirth').datepicker({ format: 'mm/dd/yyyy', }).on('input change', function(e) { // Revalidate date field when user selects/changes the date $('#validateform').bootstrapValidator('revalidateField', 'dob'); }); // Initialize BootstrapValidator $('#validateform').bootstrapValidator({ feedbackIcons: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, fields: { full_name: { validators: { stringLength: { min: 5, message: 'Please enter your full name with minimum 5 characters' }, notEmpty: { message: 'Please enter your full name' } } }, password: { validators: { notEmpty: { message: 'Please enter your password' } } }, confirmPassword: { validators: { notEmpty: { message: 'Please confirm your password' }, identical: { field: 'password', message: 'Passwords do not match' } } }, email: { validators: { notEmpty: { message: 'Please enter your email address' }, emailAddress: { message: 'Please enter a valid email address' } } }, dob: { validators: { notEmpty: { message: 'The date is required' }, date: { format: 'MM/DD/YYYY', message: 'The date is not valid' }, callback: { message: 'Your age must be between 14 and 50 years old', callback: function(value, validator) { const birthDate = new Date(value); const today = new Date(); let age = today.getFullYear() - birthDate.getFullYear(); const monthDiff = today.getMonth() - birthDate.getMonth(); if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) { age--; } return age >= 14 && age <= 50; } } } } }, onSuccess: function(e, data) { // Prevent default form submission to keep modal visible e.preventDefault(); // Show success modal $('.modalMy').modal('show'); } }); }); </script> </body> </html>
Quick Notes:
- I cleaned up error messages to be more user-friendly
- The age calculation is accurate (it checks if the user's birthday has passed this year before counting the full year)
- Fixed missing HTML structure to ensure the form and modal work as expected
内容的提问来源于stack exchange,提问作者Nagarakanti Saiprem

