Write jQuery code to validate that a field is not empty before submit
Description: If the name field is empty, stop the form and show the message “Name is required”.
Hint:
- Use the
submitevent,e.preventDefault()and.val().trim().
HTML of the page
<form id="form">
<input type="text" id="name" value=" ">
<span id="error"></span>
<button type="submit">Send</button>
</form>
Solution
$('#form').on('submit', function (e) {
if ($('#name').val().trim() === '') {
e.preventDefault();
$('#error').text('Name is required');
} else {
$('#error').text('');
}
});
$('#form').trigger('submit');
console.log($('#error').text());
Console output
Name is required
How it works
- The field has only spaces, so after
trim()it is empty. preventDefault()stops the browser from sending the form.
Read jQuery Forms.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |