How to Create a jQuery Validation Message?

Estimated read time 2 min read

To create a jQuery validation message, you can follow these steps:

  1. Create an HTML form element with some input fields that you want to validate. Here’s an example:
<form>
  <label for="username">Username:</label>
  <input type="text" id="username" name="username">

  <label for="password">Password:</label>
  <input type="password" id="password" name="password">

  <button type="submit">Submit</button>
</form>
  1. Include the jQuery library in your HTML file. Here’s an example:
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  1. Add some JavaScript code that will validate the input fields when the user submits the form, and show an error message if any field is invalid. Here’s an example:
$('form').submit(function(event) {
  var username = $('#username').val();
  var password = $('#password').val();

  if (username == '') {
    event.preventDefault();
    $('#username').addClass('error');
    $('<div class="error-message">Please enter a username</div>').insertAfter('#username');
  } else {
    $('#username').removeClass('error');
    $('.error-message').remove();
  }

  if (password == '') {
    event.preventDefault();
    $('#password').addClass('error');
    $('<div class="error-message">Please enter a password</div>').insertAfter('#password');
  } else {
    $('#password').removeClass('error');
    $('.error-message').remove();
  }
});

This code will listen for the form submission event, and validate the username and password input fields. If either field is empty, it will prevent the default form submission behavior, add an “error” class to the invalid field, and insert a new error message element after the field. If the field is valid, it will remove the “error” class and remove any existing error message elements.

  1. Add some CSS code to style the error message element. Here’s an example:
.error {
  border-color: red;
}

.error-message {
  color: red;
  font-size: 12px;
  margin-top: 5px;
}

This code will add a red border to the invalid input field, and style the error message element with red text and a smaller font size.

That’s it! Now, when the user submits the form without entering a username or password, the validation message will appear below the invalid field. You can customize the validation rules and error message styles by modifying the JavaScript and CSS code.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply