2
我正在爲我的.NET MVC 4應用程序編寫自定義驗證。這是使用參數的第一個驗證,我發現一些麻煩來獲取它。無法訪問.NET MVC客戶端驗證上的ValidationParameters
這是我的C#代碼:
ValidationAttribute:
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;
}
}
}
ModelClientValidationRule:
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;
});
許多謝謝尋求幫助!
最後!畢竟這段時間我最終使用了一種替代方法,即從HTML屬性中獲取minLength,而不是從「params」中獲取。但是這個解決方案好多了,謝謝! –
是的,傳遞給客戶端的參數並沒有很好的記錄。我在網上的其他地方找到它,同時尋找其他東西。我希望這可以幫助其他人(包括我自己)在未來。問候! –