簡體   English   中英

Jquery驗證使用默認[必需]但不適用於自定義類

[英]Jquery Validation Works with Default [Required] but not with custom class

基於以下鏈接: 多語言 - 數據注釋創建一系列類來翻譯數據注釋的文本。 服務器端的一切正常,但客戶端驗證不起作用。

如果我使用: [System.ComponentModel.DataAnnotations.Required] public string Name { get; set; } [System.ComponentModel.DataAnnotations.Required] public string Name { get; set; }

客戶端驗證工作正常,但如果我使用:

[Infrastructure.Required]//My custom class public string Name { get; set; }

它僅適用於服務器端。

這是我目前使用的課程:

namespace project.Infrastructure
{
public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute
{
    private string _displayName;
    public RequiredAttribute()
    {
        ErrorMessageResourceName = "Validation_Required";
    }
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        _displayName = validationContext.DisplayName;
        return base.IsValid(value, validationContext);
    }
    public override string FormatErrorMessage(string name)
    {
        var msg = WebsiteTranslations.GetTranslationErrorMessage(Settings.LanguageId, "Required", WebsiteTranslations.GetTranslation(name, 1, Settings.LanguageId));
        return string.Format(msg, _displayName);
    }
    public System.Collections.IEnumerable GetClientValidationRules(System.Web.Mvc.ModelMetadata metadata, ControllerContext context)
    {
        return new[] { new ModelClientValidationRequiredRule((ErrorMessage)) };
    }
  }
}

我從這篇文章中得到了答案: validation-type-names-in-unobtrusive GetClientValidationRules方法是這樣的:

    public IEnumerable GetClientValidationRules(System.Web.Mvc.ModelMetadata metadata, ControllerContext context)
    {
        var clientValidationRule = new ModelClientValidationRule()
        {
            ErrorMessage = FormatErrorMessage(ErrorMessage),
            ValidationType = "required"
        };
        yield return new[] { clientValidationRule };
    }

在Global.asax里面的Application_Start中:

      DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredAttribute), typeof(RequiredAttributeAdapter));
        DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(StringLengthAttribute), typeof(StringLengthAttributeAdapter));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM