小编Kri*_*zak的帖子

自定义验证不会触发客户端

我正在编写一个自定义属性,以便在另一个属性具有指定值时要求viewmodel中的属性.

我使用这篇文章作为参考:RequiredIf Conditional Validation Attribute

但是一直遇到IClientModelValidator的.NET Core修订版的问题.具体来说,服务器端验证按预期工作,ModelState.IsValid返回false,ModelState错误包含我的自定义错误代码.在不同版本的验证器之间进行翻译时,我觉得我遗漏了一些东西.

旧(工作)解决方案具有以下内容:

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata,
    ControllerContext context)
{
    var rule = new ModelClientValidationRule
    {
        ErrorMessage = ErrorMessageString,
        ValidationType = "requiredif",
    };
    rule.ValidationParameters["dependentproperty"] =
        (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(PropertyName);
    rule.ValidationParameters["desiredvalue"] = DesiredValue is bool
        ? DesiredValue.ToString().ToLower()
        : DesiredValue;

    yield return rule;
}
Run Code Online (Sandbox Code Playgroud)

基于此处概述的IClientModelValidator的更改:https://github.com/aspnet/Announcements/issues/179我编写了以下方法:

    public void AddValidation(ClientModelValidationContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }
        MergeAttribute(context.Attributes, "data-val", "true");

        var errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
        MergeAttribute(context.Attributes, "data-val-requiredif", errorMessage);

        MergeAttribute(context.Attributes, "data-val-requiredif-dependentproperty", PropertyName);

        var …
Run Code Online (Sandbox Code Playgroud)

javascript c# asp.net-core-mvc asp.net-core

6
推荐指数
1
解决办法
743
查看次数

标签 统计

asp.net-core ×1

asp.net-core-mvc ×1

c# ×1

javascript ×1