jQuery validation group with Remote Validation MVC 3

698 Views Asked by At

I want to validate a date of birth with a RemoteValidation/jQuery from 3 selectors. I want to check if a user is 18 or older. But atm i'm having some trouble to group them so they are invalid/valid together and with only one errormessage.

Goal: i want to validate all 3 elements as a group (jquery validator group) with the same RemoteValidation when you change anyone of them.

Anyone got any idea how to solve this?

View:

@Html.DropDownListFor(m => m.BirthYear, Model.BirthYearList)
@Html.DropDownListFor(m => m.BirthMonth, Model.BirthMonthList)
@Html.DropDownListFor(m => m.BirthDay, Model.BirthDayList)

Model

[Remote("IsValidCustomerBirthDate", "JsonValidation", AdditionalFields = "BirthDay, BirthMonth", ErrorMessageResourceName = "InvalidCustomerBirthDate", ErrorMessageResourceType = typeof(Error))]
[Required]
public int BirthYear { get; set; }

[Remote("IsValidCustomerBirthDate", "JsonValidation", AdditionalFields = "BirthYear,  BirthDay", ErrorMessageResourceName = "InvalidCustomerBirthDate", ErrorMessageResourceType = typeof(Error))]
[Required]
public int BirthMonth { get; set; }

[Remote("IsValidCustomerBirthDate", "JsonValidation", AdditionalFields = "BirthYear, BirthMonth", ErrorMessageResourceName = "InvalidCustomerBirthDate", ErrorMessageResourceType = typeof(Error))]
[Required]
public int BirthDay { get; set; }

RemoteValidation function

[HttpGet]
public JsonResult IsValidCustomerBirthDate(int birthYear, int birthMonth, int birthDay)
    {
        try
        {
            var dateOfBirth = new DateTime(birthYear, birthMonth, birthDay);
            var ageCalculator = new AgeCalculator();

            if (ageCalculator.GetAge(dateOfBirth) >= AgeLimit)                   
            {
                return Json(true, JsonRequestBehavior.AllowGet);
            }
        }
        catch (ArgumentException)
        {

        }            

        return Json(false, JsonRequestBehavior.AllowGet);
    }

I've been struggling some with groups in validate() but not getting anywhere.

Thanks for any kind of inputs. (I'm a front-end developer so please be more instructive if it's complicated C# code).

Kind Regards / Magnus

2

There are 2 best solutions below

0
On

I'll put the validation only on BirthDay dropdown (because is the last one) and then trigger the validation of this one on the 2 other fields change event.

$("#BirthYear, #BirthMonth").change(function(e){
    $("#BirthDay").valid();
});
0
On

I also take the same approach that kpull1 mentioned. Expanding on his answer a bit, I wrote this helper method that finds each remotely validating element that has "additional fields," and then causes validation on said element to fire each time one of those fields changes.

// I hate naming things
function initializeRemotelyValidatingElementsWithAdditionalFields($form) {
    var remotelyValidatingElements = $form.find("[data-val-remote]");

    $.each(remotelyValidatingElements, function (i, element) {
        var $element = $(element);

        var additionalFields = $element.attr("data-val-remote-additionalfields");

        if (additionalFields.length == 0) return;

        var rawFieldNames = additionalFields.split(",");

        var fieldNames = $.map(rawFieldNames, function (fieldName) { return fieldName.replace("*.", ""); });

        $.each(fieldNames, function (i, fieldName) {
            $form.find("#" + fieldName).change(function () {
                // force re-validation to occur
                $element.removeData("previousValue");
                $element.valid();
            });
        });
    });
}

Call the function like so:

$(document).ready(function() {
    initializeRemotelyValidatingElementsWithAdditionalFields($("#myFormId"));
});