问题
I am trying to get client-side validation working with custom annotations in an ASP.NET MVC app. Sorry for the somewhat lengthy post.
Here is the custom attribute:
public class CustomStringLengthAttribute : ValidationAttribute, IClientValidatable
{
public int MaxLength { get; private set; }
public int MinLength { get; set; }
public CustomStringLengthAttribute(int maxLength)
: base(GetDefaultErrorMessage)
{
MaxLength = maxLength;
}
private static string GetDefaultErrorMessage()
{
return "Max length {1}";
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name, MaxLength, MinLength);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
...
if (length > MaxLength || length < MinLength)
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule();
rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
rule.ValidationType = "customstringlength";
rule.ValidationParameters.Add("max", MaxLength);
rule.ValidationParameters.Add("min", MinLength);
yield return rule;
}
}
I use the attribute in my view model:
[CustomStringLength(25)]
public virtual string BillAddress1 { get; set; }
The data- attributes appear to be generated as they should:
<input data-val="true" data-val-customstringlength="Max length 25" data-val-customstringlength-max="25" data-val-customstringlength-min="0" id="BillAddress1" name="BillAddress1" type="text" value="">
The client-side validation kicks in, but I get "Uncaught TypeError: Cannot read property 'call' of undefined" in jquery.validate.js
This is from "check: function(element) ..." in jquery.validate.js - the method variable is "undefined":

Looking at the rules variable explains why the method variable is undefined - for some reason the array containing the min and max parameters is "undefined" instead of being named "customstringlength":

But why is it "undefined"??
Here is my customValidation.js, where I add the adapter, etc:
(function ($) {
if ($.validator && $.validator.unobtrusive) {
$.validator.unobtrusive.adapters.addMinMax("customstringlength", "min", "max");
$.validator.addMethod("customstringlength", function (value, element, min, max) {
if (value) {
if (value.length < min || value.length > max) {
return false;
}
}
return true;
});
}
}(jQuery));
Here is where I invoke the validation for the form:
function validateForm(form) {
prepareValidationScripts(form);
var validator = $.data(form[0], 'validator');
return validator.form();
}
function prepareValidationScripts(form) {
if (form.executed)
return;
form.removeData("validator");
$.validator.unobtrusive.parse(document);
form.executed = true;
}
I have been staring at this for too long - what am I missing??
回答1:
I finally got this working! I decided not to try to use the "convenience" addMinMax adapter, but instead write a custom adapter. Here is the updated customValidation.js (everything else stays the same):
(function ($) {
if ($.validator && $.validator.unobtrusive) {
$.validator.unobtrusive.adapters.add('customstringlength', ['min', 'max'], function(options) {
options.rules['customstringlength'] = {
min: options.params.min,
max: options.params.max,
};
options.messages['customstringlength'] = options.message;
});
$.validator.addMethod('customstringlength', function (value, element, params) {
if (value) {
if (value.length < params.min || value.length > params.max) {
return false;
}
}
return true;
});
}
}(jQuery));
来源:https://stackoverflow.com/questions/24298112/client-side-custom-annotation-validation-not-working