jquery validation form submit
jQuery Validation Form Submit
When submitting a form, it is important to ensure that the user inputs valid data. This is where jQuery validation comes in handy. It allows us to validate user input before the form is submitted to the server.
Steps for jQuery Validation
- Include jQuery and jQuery validation plugin in your HTML file:
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
- Create a form in HTML:
<form id="myForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br><br>
<button type="submit">Submit</button>
</form>
- Add validation rules to your form using jQuery:
<script>
$(document).ready(function() {
$("#myForm").validate({
rules: {
name: "required",
email: {
required: true,
email: true
}
},
messages: {
name: "Please enter your name",
email: {
required: "Please enter your email",
email: "Please enter a valid email address"
}
}
});
});
</script>
- Handle the form submission using jQuery:
<script>
$(document).ready(function() {
$("#myForm").submit(function(e) {
e.preventDefault();
if ($("#myForm").valid()) {
// submit the form
}
});
});
</script>
Here, we first prevent the default form submission behavior using e.preventDefault()
. Then, we check if the form is valid using $("#myForm").valid()
. If it is valid, we can submit the form to the server.
Alternatively, we can also use the submitHandler
option to handle the form submission:
<script>
$(document).ready(function() {
$("#myForm").validate({
rules: {
name: "required",
email: {
required: true,
email: true
}
},
messages: {
name: "Please enter your name",
email: {
required: "Please enter your email",
email: "Please enter a valid email address"
}
},
submitHandler: function(form) {
// submit the form
}
});
});
</script>
Here, we add a submitHandler
function to validate the form and submit it to the server.