簡體   English   中英

使用 IClientModelValidator 在 ASP.NET Core 中帶有參數的自定義客戶端驗證屬性

[英]Custom client side validation attribute with parameter in ASP.NET Core using IClientModelValidator

我正在嘗試創建我自己的客戶端驗證屬性,該屬性將在提交時驗證表單的屬性。 我一直在參考以下 Microsoft 文檔: https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.1#custom-validation

我不確定如何將驗證規則添加到 jQuery 的驗證器對象。 這是我已經走了多遠:

我的 ValidationAttribute 如下

public class CannotEqualValue : ValidationAttribute, IClientModelValidator
{
    private readonly string _value;

    public CannotEqualValue(string value)
    {
        _value = value;
    }

    public void AddValidation(ClientModelValidationContext context)
    {
        if (context == null)
            throw new ArgumentNullException(nameof(context));

        MergeAttribute(context.Attributes, "data-val", "true");
        MergeAttribute(
            context.Attributes, "data-val-cannotbevalue", GetErrorMessage()); //???
        MergeAttribute(
            context.Attributes, "data-val-cannotbevalue-value", _value);      //???
    }

    protected override ValidationResult IsValid(
        object value, 
        ValidationContext validationContext)
    {
        var category = (Category) validationContext.ObjectInstance;

        if (category.Name == _value)
            return new ValidationResult(GetErrorMessage());

        return ValidationResult.Success;
    }

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

        attributes.Add(key, value);
        return true;
    }

    private string GetErrorMessage()
    {
        return $"Name cannot be {_value}.";
    }
}

ValidationAttribute 用於像這樣的模型

public class Category
{
    [Key]
    public int Id { get; set; }

    [Required(ErrorMessage = "Name is required and must not be empty.")]
    [StringLength(200, ErrorMessage = "Name must not exceed 200 characters.")]
    [CannotEqualValue("Red")]
    public string Name { get; set; }
}

我在我的頁面中引用了 jQuery 驗證和不引人注目的。

我不確定如何將規則添加到 jQuery 的驗證器對象:

$.validator.addMethod("cannotbevalue",
    function(value, element, parameters) {
        //???
    });

$.validator.unobtrusive.adapters.add("cannotbevalue",
    [],
    function(options) {
        //???
    });

您在AddValidation()方法中的MergeAttribute(..)代碼行是正確的,並且將為客戶端驗證添加data-val-*屬性。

你的腳本需要

$.validator.addMethod("cannotbevalue", function(value, element, params) {
    if ($(element).val() == params.targetvalue) {
        return false;
    }
    return true;
});

$.validator.unobtrusive.adapters.add('cannotbevalue', ['value'], function(options) {
    options.rules['cannotbevalue'] = { targetvalue: options.params.value };
    options.messages['cannotbevalue'] = options.message;
});

暫無
暫無

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

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