我正在爲Visual Studio 2015中的驗證開發ASP.NET MVC 5.2.3自定義數據註釋。它需要採取任意數量的字段並確保如果有值,他們都必須有價值;如果它們全部爲空/空白,則應該沒問題。ASP.NET MVC自定義多字段驗證
舉幾個例子幫助:
- ASP.NET MVC implement custom validator use IClientValidatable
- MVC Form Validation on Multiple Fields
- http://www.macaalay.com/2014/02/24/unobtrusive-client-and-server-side-age-validation-in-mvc-using-custom-data-annotations/
但是,我不知道該怎麼辦,你有一個客戶端驗證未知數量的字段被驗證。
您如何通過IClientValidatable
接口的GetClientValidationRules()
方法的實現將它傳遞給客戶端?
另外,如何將這個新的數據註釋應用到我的視圖模型的屬性?它會是這樣嗎?
[MultipleRequired("AppNumber", "UserId", /* more fields */), ErrorMessage = "Something..."]
[DisplayName("App #")]
public int AppNumber { get; set; }
[DisplayName("User ID")]
public int UserId { get; set; }
這裏的,據我可以與MultipleRequiredAttribute
自定義數據的註釋類獲得:
public class MultipleRequiredAttribute : ValidationAttribute, IClientValidatable
{
private readonly string[] _fields;
public MultipleRequiredAttribute(params string[] fields)
{
_fields = fields;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// If any field has value, then all must have value
var anyHasValue = _fields.Any(f => !string.IsNullOrEmpty(f));
if (!anyHasValue) return null;
foreach (var field in _fields)
{
var property = validationContext.ObjectType.GetProperty(field);
if (property == null)
return new ValidationResult($"Property '{field}' is undefined.");
var fieldValue = property.GetValue(validationContext.ObjectInstance, null);
if (string.IsNullOrEmpty(fieldValue?.ToString()))
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
return null;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = ErrorMessage,
ValidationType = "multiplerequired"
};
}
}
謝謝。
你建立jQuery驗證JS在客戶端插件自定義函數 – Steve
首先閱讀[ASP.NET MVC 3驗證完整指南 - 第二部分](http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net -mvc -3-部分-2)。在你的'GetClientValidationRules()'方法中,你添加一個'ModelClientValidationRule',你可以在其中傳遞一個逗號分隔的屬性名稱列表 - 也就是你的'fields'值 - 可以在客戶端腳本中解析和使用如果你有問題,請告訴我,我會添加一個答案,但不會有機會幾個小時) –
謝謝@StephenMuecke!我的問題之一是如何將價值傳遞給客戶。 – Alex