0
我想在ASP.NET MVC應用程序中使用自定義註釋來獲取客戶端驗證。對不起有點冗長的帖子。客戶端自定義註釋驗證不起作用
這是自定義屬性:
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;
}
}
我使用屬性在我的視圖模型:
[CustomStringLength(25)]
public virtual string BillAddress1 { get; set; }
數據 - 屬性顯示中產生,因爲他們應該:
<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="">
客戶端驗證啓動,但我得到「Uncaught TypeError:無法讀取j中的未定義的屬性'調用' query.validate.js
這是從 「校驗:功能(元件)...」 在jquery.validate.js - 所述方法變量是 「未定義」:
綜觀規則可變解釋了爲什麼方法變量是未定義 - 由於某種原因含有最小和最大參數陣列是「未定義」,而不是被命名爲「customstringlength」:
但爲什麼是「未定義」?
這裏是我的customValidation.js,在那裏我添加適配器等:
(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));
這裏就是我援引的形式驗證:我已經在這個一直盯着
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;
}
太久了 - 我錯過了什麼?
請不要發佈代碼或錯誤消息圖片的圖片。只發布實際的代碼或錯誤,以便此內容可供搜索。 – Sparky