Matthew Dresser
Matthew Dresser

Reputation: 11442

jQuery Validate Unobtrusive - hook into error event of an individual input

I am building a site with ASP.NET MVC and am using the jQuery validate unobtrusive library. I want to know if there is a way to hook into the event where a validation message is displayed e.g. at the point where a user types something invalid (as opposed to the instant when they click the submit button).

The reason I want to do this is because I am styling my error messages like mini popups which appear above the field which has the error - i.e. using absolute positioning. Due to the fact that a single field could have various different validation errors, I want to be able to set the position of the field correctly accounting for the variable height of the message. I will also need to handle this event so I can apply a class for a red border round the input element.

Upvotes: 6

Views: 4532

Answers (2)

Walter
Walter

Reputation: 1855

There is a great script here: https://gist.github.com/beccasaurus/957732/ that sets up hooks for different events in jQuery.validate. It lets you bind to a bunch of different events, in your case it would look like this:

$(function () {
    $('form').addTriggersToJqueryValidate();
    $('form').bind("elementValidation", function (event, element, result) {
        console.log("Something is invalid");
    });
})

Very handy!

Upvotes: 7

ozhug
ozhug

Reputation: 1083

you can validate and form element when the users moves to the next element in form with

$("form#myformid").validate().element("#ModelObject_NameofField");

and use the errorplacement for each element as shown in this previous answer

jquery - how to use errorPlacement for a specific element?

your popup <div/> should grow with the text inside of it so you should only need to anchor the bottom left or right next to element.

Upvotes: 0

Related Questions