我正在为我的 .NET MVC 4 应用程序编写自定义验证。这是第一个使用参数的验证,我发现了一些麻烦。
这是我的 C# 代码:
验证属性:
namespace Validations
{
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class MinRequiredPasswordLengthValidationAttribute : ValidationAttribute, IClientValidatable
{
public MinRequiredPasswordLengthValidationAttribute()
: base("The password is invalid")
{
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name.ToLower(), Membership.MinRequiredPasswordLength);
}
public override bool IsValid(object value)
{
if (value == null || String.IsNullOrEmpty(value.ToString()))
{
return true;
}
return value.ToString().Length >= Membership.MinRequiredPasswordLength;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
ModelClientMinRequiredPasswordLengthValidationRule rule = new ModelClientMinRequiredPasswordLengthValidationRule(FormatErrorMessage(metadata.GetDisplayName()), Membership.MinRequiredPasswordLength);
yield return rule;
}
}
}
模型客户端验证规则:
namespace Validations
{
public class ModelClientMinRequiredPasswordLengthValidationRule : ModelClientValidationRule
{
public ModelClientMinRequiredPasswordLengthValidationRule(string errorMessage, int minRequiredPasswordLength)
{
ErrorMessage = errorMessage;
ValidationType = "minrequiredpasswordlength";
ValidationParameters.Add("minlength", minRequiredPasswordLength);
}
}
}
这是JS代码,我的问题:
jQuery.validator.addMethod("minrequiredpasswordlength", function (value, element, params) {
if (value.length == 0) {
return true; //empty
}
return true; //dummy return
}, "");
jQuery.validator.unobtrusive.adapters.add("minrequiredpasswordlength", {}, function (options) {
//XXX Here I should get the minlength parameter, but 'options' is a empty object
options.messages["minrequiredpasswordlength"] = options.message;
});
非常感谢您的帮助!