How to jQuery Validation On Button Click

jQuery form validation is one of the easiest ways to validate form fields on any web page. We can validate text fields, text-area fields, email fields, password fields, etc. just by simple jQuery validate() function.

To apply validation on a simple web form, we just have to initialize validate() function on page load. But it won’t work on Ajax form submission. So, how to apply jQuery validation on Ajax form submit requests.

On Button Click jQuery Form Validation

The answer is quite effortless and straightforward to implement. We just have to use a default valid() method of jQuery on a button click event.

Syntax:

.valid()

Read Also: jQuery Form Validation

The below code shows the method of implementation of a valid() method in a compact way.

<!DOCTYPE html>
<html>
<head>
	<title>How to Validate Form Using jQuery On Button Click</title>
</head>
<body>
<form id="form">
	<label for="name">Name:</label>
	<input type="text" id="name" name="name" required/>
    <input type="button" onclick="ajax_submit()" value="Submit"/>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script>
function ajax_submit() {
	if($("#form").valid()){
            var name = document.getElementById("name").value;
            var data = new FormData();
            data.appendChild("name", name);
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("demo").innerHTML = this.responseText;
                }
            };
            xhttp.open("POST", "ajax_request_url", true);
            xhttp.send(data);
	}
}
</script>
</body>
</html>

Explanation

In the above code we used $(“#form”).valid() which gets the form by ID and validates it for empty fields.

Conclusion

As said earlier, jQuery is the easiest method to validate a form. I hope you get a basic understanding of jQuery validations.

jQuery has more advanced validation for HTML forms it is suggested to explore them all in great detail.

Keep Exploring and Enjoy Scripting 🙂

Leave a Reply

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