Reputation: 6045
I applied AUTO COMPLETE functionality to one of my textboxes and i am sucessfully populating data upon character typing and now i need something Unique functionality to my texbox .
My requirement is I dont want user to enter JUNK values and save rather i prefer user to select from list . One thing just in case if user typed something and tried to save means the VALIDATION should fail at any cost and only things only work when i select from list and save .
My Working Code :
$('#txtSalesPerson1').autocomplete({
source: function (request, response) {
$.ajax({
url: "/api/Values/" + request.term,
dataType: 'json',
type: 'Post',
success: function (data) {
response($.map(data.slice(0, 10), function (item) {
return {
label: item.Text,
value: item.Value
}
}));
}
})
},
select: function (event, ui) {
$('#txtSalesPerson1').val(ui.item.label);
$('#Id').val(ui.item.value);
return false;
},
minLength: 1
});
Any help on this is pretty much appreciated Thank you .
What i am thinking so far :
Tought 1 : I have to compare the entered value of textbox with data i get and Validate accordingly But my TL feels thats a big way and you can't use that .
Tought 2 : On leave of focus from textbox thinking to validate but again it will paritially make me to go to server Tought 1 way .
Friends i have no clue for now to move a head with the best possible approcah .
Regards
Upvotes: 0
Views: 98
Reputation: 7172
If I had to tackle this, I'd change the ignore settings on the jquery validate to pick up hidden fields.
$.validate.defaults.ignore="";
You'll need to rebind your form validator after changing this
On top of this, I would add the following to the model in your view
[Required]
[Range(1, int.maxvalue)
public int Id {get;set; }
This way the validation will only pass server and client side if a value has been selected.
Bit of a brute force approach.
If you do it that way, remember to overload the search function on the autocomplete to clear #Id of a value so if they search again, they are forced to reselect an entry
The other method, would be to do something like an OnBegin handler on the form submit (if you are using ajax.beginform, otherwise bind up a submit handler) and check for $("#Id").val() being greater than zero and returning false to stop the form submitting if it isn't.
You will need to roll a feedback system so the user knows what they have done wrong though with that method
Upvotes: 1