Model 自訂驗證

  • 繼承ValidationAttribute,然後覆寫IsValid方法。
  • 如果要提供Client端驗證,則需實作 IClientValidatable 介面的GetClientValidationRules方法。
public class ContainWordAttribute:ValidationAttribute,IClientValidatable
{
    private string _word { get; set; }

    public ContainWordAttribute(string word)
    {
        this._word = word;
    }

    public override bool IsValid(object value)
    {
        if (value is string)
        {
            if (value.ToString().Contains(this._word))
            {
                return true;
            }
        }
        return false;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
        ModelMetadata metadata
       , ControllerContext context)
     {
        ModelClientValidationRule rule = new ModelClientValidationRule
        {
            ValidationType = "containword",
            ErrorMessage = FormatErrorMessage(metadata.GetDisplayName())
        };

        rule.ValidationParameters["word"] = this._word;
        yield return rule;
      }
  }
}
  • 新增Javascript 前端驗證功能,然後將其掛載到前端頁面上。 這段JavaScript的邏輯規則是將你覆寫的IsValid這個Method中的C#語法轉換成JavaScript語法。
$.validator.unobtrusive.adapters.add('containword', ['word'], function (options) {
    options.rules["containword"] = { word: options.params.word };
    options.messages["containword"] = options.message;
});

$.validator.addMethod('containword', function (value, element, param) {

    if (value.indexOf(param.word)!=-1) {
        return true;
    }
    return false;
});

完成以上步驟就可以自訂驗證屬性套用到Model了

public class Book
{
  [ContainWord("MVC", ErrorMessage = "請輸入包含MVC的書")]
  public string Name { get; set; }
}

CustomValidation範例

results matching ""

    No results matching ""