Forcing a revalidate on mvc3 unobtrusive remote validation
Asked Answered
D

1

10

It's a classic login flow. The user can choose between 'new user' or 'existing user'. If the user is new, the name in the login box should validate against the server to see if the username is unique, if it's an existing user this check will be skipped since we expect the username to be taken already (ofcourse).

I added a [Remote] attribute on the viewmodel and added the radiobutton for new/exiting user as 'additional fields'. This way the remote validation will just return true if it's an existing user, and check the database if it's not, to see if the username is taken.

This works great, except when the user decides to change the radiobutton (new/existing) after entered a username (and the remote validation has run). Since remote validation is only automatically run when the username changes (that's the property with [Remote] attribute), changing the radiobutton alone, will not have it run again.

So my problem is, how can i force the remote validation to run again? I tried the usual hacks by triggering a change/focus/blur event on the username input field, but the call is not triggered. I considered adding a similar [Remote] on the radiobutton, but that would really complicate things with two equal looking error messages, placed at the same absolute position.

Is there any way to trigger a revalidation?

Dyedinthewool answered 11/4, 2011 at 7:41 Comment(0)
V
19

I believe that jquery validation can be triggered using $("#formID").validate()

Some more options can be found in the docs: http://docs.jquery.com/Plugins/validation, and at Brad Wilson's blog (you can also find some info in the comments)

Have you looked into the Data attributes that the input has, maybe it's cached? something like this.

EDIT: Just for clarification, this is how i got it to work

$('#UserName').removeData('previousValue');
$('form').validate().element('#UserName');
Virtuosic answered 11/4, 2011 at 7:55 Comment(3)
Only if validation hasn't been run already, which it has. Also for some reason remote validation seem to not run again, even if i remove the validator on the form, and reparse the whole form again (other non-remote validations are run again if i do that)Lindsaylindsey
You were spot on with the caching. I thought i tried it (removed ALL data and then revalidation ALL of the form), but the link had it allLindsaylindsey
Just wanted to add that "previousValue" IS the name of the attribute although I did not see anything corresponding to it when inspecting the page.Hyperventilation

© 2022 - 2024 — McMap. All rights reserved.