jQuery Validation asp.net mvc 3
I have a very simple model I'm working with that I'm trying to implement jQuery validation with.
Model:
public class Escalation {
public int Id { get; set; }
public int Primary { get; set; }
public int Backup { get开发者_如何转开发; set; }
public virtual Contact PrimaryContact { get; set; }
public virtual Contact BackupContact { get; set; }
}
What I'm trying to do is via the UI enforce that both primary and backup are valid. however, since these are contacts and we have thousands of them I don't want to put them all into a <select>
control. I am trying to use a <input>
and have jquery.autocomplete() help the user select a valid contact. But I want to ensure that it is not only required but valid.
What I've tried so far is subscribing to the autocomplete event 'select' and I update a hidden field with the value that is selected and everything works fine. However, if the user doesn't actually select a person or types in some invalid data everything breaks.
Perhaps I'm making this simple form overly complex? Any suggestion on how to achieve what I'm trying to accomplish would be greatly appreciated.
Here is an example of what I'm trying to accomplish. http://jsfiddle.net/2wCQs/2/
It sounds as if you need to make a ajax call back to validate first that the ID of the contact they input is valid.
Subscribe to the onblur event if the ID is extended, or you can use the ontextchanged event if you want to validate on the fly (I suggest using a timeout so that a person typing incremementally doesn't spawn 15 ajax calls when typing 15 characters).
This kind of validation should be done on the server where you can check against the database that the selected value actually is ok. It should be done when you save the form. To improve user experience you might want to do it on client side too and that's where "remote validation" comes in. See http://davidhayden.com/blog/dave/archive/2011/01/04/ASPNETMVC3RemoteValidationTutorial.aspx
maybe you can use change event of autocomplete to see if there is something selected, if the user doesn't actually select item or types in some invalid data you will know it on change event instead of the select event which fires only when an item is selected.
change: function( event, ui ) {
alert( ui.item ?
"changed to/ selected: " + ui.item.value + " aka " + ui.item.Id :
"Nothing selected, input was " + this.value );
}
精彩评论