简体   繁体   中英

Add MVC3 unobtrusive validation (addMinMax)

I have such attribute:

public class AgeRangeAttribute:ValidationAttribute,IClientValidatable
    {
public int MinAge { get; set; }

        public int MaxAge { get; set; }

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            ModelClientValidationRule rule = new ModelClientValidationRule
                                                {
                                                    ErrorMessage = ErrorMessage,
                                                    ValidationType = "agerange"
                                                };
            if (MinAge != int.MinValue)
            {
                rule.ValidationParameters.Add("minage", DateTime.Now.AddYears(-MinAge).ToShortDateString());
            }
            if(MaxAge != int.MinValue)
            {
                rule.ValidationParameters.Add("maxage", DateTime.Now.AddYears(-MaxAge).ToShortDateString());
            }
            yield return rule;
        }
}

and JS validator representation:

jQuery.validator.addMethod("agerangemin", function (value, element, param) {
    var date = setDate(new Date(),value);
    var expected = setDate(new Date(), param);
    return date <= expected;
});

jQuery.validator.addMethod("agerangemax", function (value, element, param) {
    var date = setDate(new Date(), value);
    var expected = setDate(new Date(), param);
    return date > expected;
});

jQuery.validator.addMethod("agerangemaxmin", function (value, element, param) {
    var date = setDate(new Date(), value);
    var expectedMin = setDate(new Date(), param[1]);
    var expectedMax = setDate(new Date(), param[0]);
    return date <= expectedMin && date > expectedMax;
});


jQuery.validator.unobtrusive.adapters.addMinMax("agerange", "agerangemin", "agerangemax", "agerangemaxmin");

and this js doesn't work (no exceptions... may be dead&:) )

but this works fine:

jQuery.validator.addMethod("agerange", function (value, element, param) {
    var date = new Date();
    date = setDate(date, value);
    var expected = setDate(new Date, param);
    return date <= expected;
});

jQuery.validator.unobtrusive.adapters.addSingleVal("agerange", "minage");

Whats wrong with it? Where is mistake?

I have some difficulties with custom unobtrusive validation a year ago. Here is what I came up with. I needed to create validator that check if user is eighteen years old.

My code:

public class CustomEiteenthValidator : ValidationAttribute, IClientValidatable
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value == null) return null;
            DateTime date = Convert.ToDateTime(value);
            var minDate = DateTime.Now.AddYears(-18);
            if (date > minDate) 
            return new ValidationResult("Employee should be more than 18 years");
            return null;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule()
            {
                ValidationType = "eiteenth",
                ErrorMessage = "Employee should be more than 18 years"
            };
            var date = DateTime.Now.AddYears(-18);
            rule.ValidationParameters["date"] = String.Format("{0:dd/MM/yyyy}", date).Replace('.', '/');
            yield return rule;
        }
    }

In model:

        [Required]
        [DataType(DataType.DateTime)]
        [CustomEiteenthValidator]            
        public DateTime Birthday { get; set; }

And some java script code in CustomDateValidation.js:

 function isFormValid() {
        var valid = true;
        $('.field-validation-error').each(function () {
            valid = false;
        });
        return valid;
    }

(function ($) {
    $.validator.addMethod("eiteenthcheck", function (val, elem, params) {
        if (!val) {
            return false;
        }
        try {
            var birthday = $.datepick.parseDate("dd/mm/yyyy", val);
            var maxBirthday = $.datepick.parseDate("dd/mm/yyyy", $(elem).attr('data-val-eiteenth-date'));
        }
        catch (e) {
            return false;
        }
        if (maxBirthday.getTime() > birthday.getTime()) return true;
        return false;
    });

    $.validator.unobtrusive.adapters.add("eiteenth", ["date"], function (options) {
        options.rules["eiteenthcheck"] = 'eiteenthcheck';
        if (options.message) options.messages["eiteenthcheck"] = options.message;
    });
} (jQuery));

In view I render textbox like that:

<%: Html.EditorFor(model => model.Birthday) %>
<%: Html.ValidationMessageFor(model => model.Birthday) %>

The last one is scripts I use:

    <script src="<%= Url.Content("~/Scripts/jquery-1.7.1.min.js") %>" type="text/javascript"></script>   
    <script src="<%= Url.Content("~/Scripts/jquery.validate.js") %>" type="text/javascript"></script>
    <script src="<%= Url.Content("~/Scripts/jquery.validate.unobtrusive.js") %>" type="text/javascript"></script>
    <script src="<%= Url.Content("~/Scripts/jquery.datepick.js") %>" type="text/javascript"></script>
    <script src="<%= Url.Content("~/Scripts/CustomDateValidation.js") %>" type="text/javascript"></script>        

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM