3
votes

I'm using MVC3 and unobtrusive validation to check my form. The user can select a facility from a list, and enter an audit name. The audit names must be unique for the facility, but can each facility can have an audit with the same name.

Model looks like this:

    [DisplayName("Audit Name")]
    [Remote("CheckAuditName", "Audit", ErrorMessage = "The audit name has already been used for this Healthcare Facility", AdditionalFields = "HealthcareFacilitySysId")]
    public string AuditName { get; set; }

    [DisplayName("Healthcare Facility")]
    public long HealthcareFacilitySysId { get; set; }

    public IEnumerable<SelectListItem> AvailableHealthcareFacilities { get; set; }

The remote validation is working, I get the right message at the right time, but I can fool it like this:

  • Select Facility 1
  • Enter an Audit name that has already been used for facility 2
  • Select Facility 2
  • Submit the form

On the Facility list's change event I have tried calling

$('form').validate().valid()
$('#AuditName').blur()

etc but I can't get the form to validate the remote method when I manually call it. Is it even possible?

1
$('form').valid(); would be adequate for the whole form. Or even $('#AuditName').valid(); should work just for the one element, assuming AuditName is the id of the select. - Sparky
@Sparky I have tried that, and while it does validate the form it omits the fields that require remote validation, which in my case is the really essential part. Thanks though - CurlyPaul
Since we're talking about JavaScript, it's essential that you also show the rendered HTML markup. - Sparky
However, if you retrigger validation on the form programmatically, all rules including the remote method also get re-evaluated. - Sparky
@CurlyPaul Did you get anything on this? I have the same scenario on Postal code and Country. - SurajS

1 Answers

2
votes

The problem is probably some caching on the validation. Try something like this:

 $("#HealthcareFacilitySysId").change(function () {

        $("#AuditName").removeData("previousValue"); //clear cache
        $("form").data('validator').element('#AuditName'); //retrigger remote call
        $('#AuditName').blur()

    });