Checking Form Validity on Submit Using jQuery

Overview

Checking form validity on submit using jQuery, I thought, should be pretty straightforward. Recently, I was working on an MVC application and had the need to hide/show a div when a form was submitted. I added some hide/show logic in the document.ready event and voila! Success! Not really. If the form was valid it worked as expected. However, if the form failed validation I couldn’t see my div. Wouldn’t be a big deal except this div was holding the validation messages so I kind of needed to see them.

Solution

So why wasn’t the div showing up? ¬†Well, after a little head scratching I realized it’s because the page is using the jquery.unobtrusive validation. In my case, seeing the following code in the view jogged my memory.

@section Scripts {
	@Scripts.Render("~/bundles/jqueryval")
}

My next challenge, and the point of this post, was to figure out how to hook into the unobtrusive validation. I started down a much more complicated route than I ended up using. I will spare you that complicated route and jump to the last page of the book.

Basically, what was needed was some jquery that hooked into the form’s submit.

$('form').submit(function () {
}

Now this code works for every form, which is what I wanted. If you want only a specific form then simmply change the selector, $(‘form’), to something more specific, like the name of your form: $(‘#myForm’). Easy peasy.

The next challenge is to check for the validity of the form. Not as complicated as I initially thought.

if ($(this).valid()) {
	// valid code here
}
else {
	// not so valid code here
}

As you can see this turned out to be a pretty simple and straightforward solution to a not so complicated issue. I have put the full code listing for the function so it is easier to see the whole solution.

$('form').submit(function () {
	if ($(this).valid()) {
		// valid code here
	}
	else {
		// not so valid code here
	}
}

Conclusion

As you can see it is pretty easy and straightforward to hook into a form submit using jQuery to test its validity. As I was looking into possible solutions to this problem I did come across what seemed to be a handy jQuery library for hooking into the validation. I have not tried this out, so if anyone is feeling adventurous try it out and let me know how it goes. The library can be found here.

For more information about .submit() and .valid() visit the jQuery API Documentation website.

Posted in Tech Tagged with: , , ,

Leave a Reply