簡體   English   中英

ASP.Net Core MVC - 自定義屬性的客戶端驗證

[英]ASP.Net Core MVC - Client-side validation for custom attribute

在以前版本的MVC框架中,將通過實現IClientValidatableGetClientValidationRules方法來實現自定義驗證。

但是在ASP.Net Core MVC中我們沒有這個接口 ,盡管我們確實有IClientModelValidator ,它定義了一個非常相似的方法。 然而,其實現永遠不會被調用。

那么 - 我們如何在ASP.NET Core MVC中為自定義屬性實現客戶端驗證?

IClientModelValidator實際上是正確的接口。 我在下面做了一個人為的示例實現。

注意: RC1和RC2之間的IClientModelValidator接口發生重大變化 兩個選項如下所示 - 兩個版本之間的其余代碼相同。

屬性(RC2及以上)

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

    public void AddValidation(ClientModelValidationContext context)
    {
        MergeAttribute(context.Attributes, "data-val", "true");
        var errorMessage = FormatErrorMessage(context.ModelMetadata.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, IClientModelValidator
{
    public override bool IsValid(object value)
    {
        var message = value as string;
        return message?.ToUpper() == "RED";
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
        ClientModelValidationContext context)
    {
        yield return new ModelClientValidationRule(
            "cannotbered",
            FormatErrorMessage(ErrorMessage));
    }
}

模型

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

視圖

@model WebApplication22.Models.ContactModel

<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>
}

暫無
暫無

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

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