简体   繁体   English

自定义验证属性不适用于自定义标签助手,仅适用于静态 html

[英]Custom validation attribute doesn't work with custom tag helper, only static html

I have been trying to implement this for a while now with no luck.我一直在尝试实现这一点,但没有运气。 I built a custom tag helper for text boxes in my project and am using it like so:我为项目中的文本框构建了一个自定义标签助手,并像这样使用它:

<text-box asp-for="@Model.PhoneNumber"></text-box>

The issue is I also created a custom validation attribute:问题是我还创建了一个自定义验证属性:

public class InputFormatAttribute : ValidationAttribute, IClientModelValidator
{
    public EInputFormat InputFormat { get; }

    public InputFormatAttribute(EInputFormat format) : base()
    {
        InputFormat = format;
    }

    public void AddValidation(ClientModelValidationContext context)
    {
        string inputMask = "";
        string secondAttribute = "";
        switch (InputFormat)
        {
            case EInputFormat.BranchNumber:
                inputMask = @"'alias': 'GCIS-branch-number'";
                break;
            case EInputFormat.BusinessNumber:
                inputMask = @"'alias': 'GCIS-business-number'";
                break;
            case EInputFormat.DirectDepositAccountNumber:
                inputMask = "'alias': 'GCIS-direct-deposit-account-number'";
                break;
            case EInputFormat.Email:
                secondAttribute = "type = email";
                break;
            case EInputFormat.FullBusinessNumber:
                inputMask = "'alias': 'GCIS-full-business-number'";
                break;
            case EInputFormat.Integer:
                inputMask = "'alias': 'GCIS-integer'";
                break;
            case EInputFormat.InternationalPhoneNumber:
                inputMask = "'alias': 'GCIS-integer'";
                secondAttribute = "type=tel";
                break;
            case EInputFormat.Percentage:
                inputMask = "'alias': 'GCIS-percentage'";
                break;
            case EInputFormat.PhoneNumber:
                inputMask = "'alias': 'GCIS-phone-number'";
                secondAttribute = "data-rule-phoneUS = true";
                break;
            case EInputFormat.PostalCode:
                secondAttribute = "data-rule-postalCodeCA = true";
                break;
            case EInputFormat.SocialInsuranceNumber:
                inputMask = "'alias': 'GCIS-social-insurance-number'";
                secondAttribute = "data-rule-minlength = 9";
                break;
            case EInputFormat.Currency:
                secondAttribute = "'alias': 'currency_en'";
                break;
        }

        if (!inputMask.Equals("")) { MergeAttribute(context.Attributes, "data-inputmask", inputMask); }
        if (!secondAttribute.Equals("")) { MergeAttribute(context.Attributes, secondAttribute, ""); }

    }
    
    bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
    {
        if (attributes.ContainsKey(key))
        {
            return false;
        }
        attributes.Add(key, value);
        return true;
    }

   public override bool IsValid(object value)
    {
        //Add more validation on submit...
        return true;
    }

}

The property in the view model using the validation attribute:使用验证属性的视图模型中的属性:

[Display(Name = "Telephone number")]    
[InputFormat(EInputFormat.PhoneNumber)]
public string PhoneNumber { get; set; } 

When I use the custom validation attribute WITH the custom tag helper the IClientModelValidator method AddValidation(ClientModelValidationContext context) never gets called and the validation work never gets finished.当我将自定义验证属性与自定义标记助手一起使用时,IClientModelValidator 方法 AddValidation(ClientModelValidationContext context) 永远不会被调用,并且验证工作永远不会完成。

However, when I don't use my tag helper and just use static HTML like so:但是,当我不使用我的标签助手而只使用静态 HTML 时:

<label class="control-label" asp-for="Phone"> @*works*@
   <span class="field-name">Phone</span`>`
</label>
<input class="form-control" asp-for="Phone">

The validation attribute methods do run....anyone have an idea of why the attribute class only works with static html and not the tag helper?验证属性方法确实运行....任何人都知道为什么属性类只适用于静态 html 而不是标签助手?

The validation attribute methods do run....anyone have an idea of why the attribute class only works with static html and not the tag helper?验证属性方法确实运行....任何人都知道为什么属性类只适用于静态 html 而不是标签助手?

Obviously, the text-box is not an officially defined tag, so you need to create it as a custom taghelper to make it the same as the input tag.显然, text-box不是官方定义的标签,因此您需要将其创建为自定义 taghelper以使其与input标签相同。

In order for the asp-for attribute of the text-box to automatically trigger the verification of the InputFormatAttribute you added to PhoneNumber , the custom taghelper you create needs to inherit from InputTagHelper .为了让text-boxasp-for属性自动触发对你添加到PhoneNumberInputFormatAttribute的验证,你创建的自定义 taghelper 需要继承自InputTagHelper

First, create the following MyCustomTagHelper class in your project:首先,在您的项目中创建以下 MyCustomTagHelper 类:

namespace MyProject.CustomTagHelper
{
    [HtmlTargetElement("text-box", Attributes = "asp-for")]
    public class MyCustomTagHelper : InputTagHelper
    {
        public MyCustomTagHelper(IHtmlGenerator htmlGenerator) : base(htmlGenerator) { }
      
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            base.Process(context, output);// the key point
            output.TagName = "input";
            output.Attributes.SetAttribute("class", "form-control");
        }
    }
}

Then, in the Views/_ViewImports.cshtml file, add the following code(here the MyProject is your project name ):然后,在Views/_ViewImports.cshtml文件中,添加以下代码(这里MyProject是您的项目名称):

@addTagHelper *, MyProject

Using the text-box tag helper as follow:使用文本框标签助手如下:

<text-box asp-for="@Model.PhoneNumber"></text-box>   

And here is the rendering html of text-box tag helper after loading your view:这是加载视图后text-box标记助手的渲染 html

<input type="text" data-inputmask="'alias': 'GCIS-phone-number'" data-rule-phoneus="true=&quot;&quot;" id="PhoneNumber" name="PhoneNumber" value="123432" class="form-control">

Here is the debug process :下面是调试过程:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM