在以前版本的MVC框架中,自定义验证将通过实现IClientValidatableGetClientValidationRules方法来实现.

然而在ASP.Net核心MVCwe do not have this interface,尽管我们有IClientModelValidator,它定义了一个非常相似的方法.然而,它的实现从未被调用.

那么,我们如何在ASP中实现自定义属性的客户端验证呢.网络核心MVC?

推荐答案

IClient型号Validator实际上是正确的接口.我在下面做了一个精心设计的示例实现.

Note: RC1和RC2之间的IClient型号Validator接口有一个breaking change.这两个选项如下所示-代码的睡觉在两个版本之间是相同的.

属性(RC2及更高版本)

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public sealed class CannotBeRedAttribute : ValidationAttribute, IClient型号Validator
{
    public override bool IsValid(object value)
    {
        var message = value as string;
        return message?.ToUpper() == "RED";
    }

    public void AddValidation(Client型号ValidationContext context)
    {
        MergeAttribute(context.Attributes, "data-val", "true");
        var errorMessage = FormatErrorMessage(context.型号Metadata.GetDisplayName());
        MergeAttribute(context.Attributes, "data-val-cannotbered", errorMessage);
    }

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

属性(RC1)

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public sealed class CannotBeRedAttribute : ValidationAttribute, IClient型号Validator
{
    public override bool IsValid(object value)
    {
        var message = value as string;
        return message?.ToUpper() == "RED";
    }

    public IEnumerable<型号ClientValidationRule> GetClientValidationRules(
        Client型号ValidationContext context)
    {
        yield return new 型号ClientValidationRule(
            "cannotbered",
            FormatErrorMessage(ErrorMessage));
    }
}

型号

public class Contact型号
{
    [CannotBeRed(ErrorMessage = "Red is not allowed!")]
    public string Message { get; set; }
}

看法

@model WebApplication22.型号s.Contact型号

<form asp-action="Contact" method="post">
    <label asp-for="Message"></label>
    <input asp-for="Message" />
    <span asp-validation-for="Message"></span>
    <input type="submit" value="Save" />
</form>

@section scripts {
    <script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
    <script>
        $.validator.addMethod("cannotbered",
            function (value, element, parameters) {
                return value.toUpperCase() !== "RED";
            });

        $.validator.unobtrusive.adapters.add("cannotbered", [], function (options) {
            options.rules.cannotbered = {};
            options.messages["cannotbered"] = options.message;
        });
    </script>
}

Asp.net相关问答推荐

从 asp.net 中的 Web.config 获取连接字符串

Linq 将复杂类型聚合成一个字符串

ASP MVC 授权除少数之外的所有操作

C# ASP.NET Core Serilog 添加类名和方法到日志(log)

使用进程外会话状态的 ASP.NET 应用程序中的 SQL Server 连接问题

在 Sessions 中存储自定义对象

asp.net dropdownlist - 在 db 值之前添加空行

asp.net mvc 中的 RedirectToAction 用法

等待本地主机,永远!

asp.net cookie、身份验证和会话超时

GridView 与嵌套类的属性绑定

ASP.NET 日期时间 Select 器

DBContext.Entry 有什么作用?

ASP.NET 中的全局资源与本地资源

如何将 LINQ 左外连接限制为一行

ASP.NET 应用程序状态与静态对象

如何判断字符串的第一个字符是否是字母,C#中的任何字母

ExecuteReader:连接属性尚未初始化

IronRuby死了吗?

jQuery Ajax 调用 - 成功设置变量值