Our app is using ASP.NET MVC 3 and I wanted to take advantage of creating a custom validation attribute that worked on both the client and server side.
The user will enter a physician number in an input field. The value is then used to check and see if the physician number entered is actually valid. This requires a call to the database. I have an ajax call inside my validation method. This works fine but only when async is set to false.
<script type="text/javascript">
$.validator.setDefaults({
debug: true,
onkeyup: false,
onclick: false,
focusInvalid: false
})
$.validator.addMethod('physician', function (value, element, params)
{
var request = $.ajax({
type: "POST",
url: "@Url.Content("~/patient/GetPhysicianById")",
data: { physicianNumber: value },
async: false,
beforeSend: function(xjhr, settings) {
var siblings = $(element).siblings('.physician-response');
//$(siblings[0]).html("<img src=\"/content/images/ajax-loader.gif\" />");
}
});
console.log(request);
if(request.responseText == "0")
return false;
return true;
});
$.validator.unobtrusive.adapters.add('physician', ['param1', 'param2'], function (options) {
options.rules['physician'] = options.params;
options.messages['physician'] = options.message;
});
</script>
On the form, there are three different physician inputs that will trigger this method. Every time blur is lost, it runs these calls again. Also runs when the user clicks save. I’m not certain if this is really the proper approach, or I should handle this validation in a separate manner.
You might take a look at the
[Remote]attribute to perform this kind of validation.