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

2

6

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.

Brahmin answered 31/10, 2013 at 17:54 Comment(0)
A
7

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!

Adamis answered 27/3, 2014 at 18:37 Comment(0)
T
0

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.

Toothache answered 1/11, 2013 at 0:10 Comment(3)
I don't want to trigger the validation of an element, instead I need to handle the event(s) when this occurs.Brahmin
are you trying to create your own method to validate an inputToothache
No, there are no custom validators.Brahmin

© 2022 - 2024 — McMap. All rights reserved.