How to Validate Empty Input Fields in a Form Using jQuery

jQuery is the most popular JavaScript framework for client-side validation. Even more, jQuery is famous for its reduced usage.

jQuery validation

jQuery has an extraordinary feature of form validation with a vast range of possible filters. We can validate empty input fields, text validation, email validation, password validations, etc…

How to use jQuery validation to check empty fields?

Here we are going to discuss empty field validation with jQuery. Empty field validation is the most basic type of validation. jQuery makes it easy to detect empty fields and also returns automatic error messages on the user screen.

Note: We have to include the jQuery validation JavaScript file to validate fields. We have included the below links, or we can download and host them on our server.

Read Also: How to Send Emails From PHPMailer Using SMTP

Links

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>

Next, we have to add the below jQuery code to validate our form via jQuery validator.

jQuery Code

<script> 
  $(document).ready(function() { 
    $("#form").validate(); 
  }); 
</script>

Example

<!DOCTYPE html>
<html>
<head>
<title>input field empty check using jQuery validation - errorsea.com</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>
</head>
<body>

<form id="form" action="target_url" method="post">
User Name: <input type="text" name="user_name" required>
<br>
Password: <input type="text" name="password" required>
<br>
<input type="submit" value="Submit">
</form>
<script>
  $(document).ready(function() {
    $("#form").validate();
  });
</script>
</body>
</html>

Explanation

  • First, we created a basic login form with the required fields and set an id #form in that form.
  • Next, we include the jQuery core library and jQuery validation library in <head> tag.
  • After that, we include jQuery code to validate empty required fields.

Read Also: How to Set Onclick Function in PHP

Conclusion

I hope now you have no doughts about jQuery empty field validation. We can also develop higher-level validation for custom forms with jQuery validation.

Enjoy Scripting πŸ™‚

Leave a Reply

Your email address will not be published. Required fields are marked *