简体   繁体   English

asp mvc core 3 自定义属性验证的客户端验证

[英]asp mvc core 3 Client side validation for a custom attribute validation

I've created a custom validation attribute like so:我创建了一个自定义验证属性,如下所示:

public class UniqueTitleAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(
           object value, ValidationContext validationContext)
        {
            var context = (MyDBContext)validationContext.GetService(typeof(MyDBContext));
            var entity = context.Pages.SingleOrDefault(e => e.Title == value.ToString());

            if (entity != null)
            {
                return new ValidationResult(GetErrorMessage(value.ToString()));
            }
            return ValidationResult.Success;
        }

        public string GetErrorMessage(string title)
        {
            return $"Title {title} is already in use.";
        }
    }

And the in the model:而在 model 中:

[UniqueTitle]
public string Title { get; set; }

And it works great, however I would also like to be able to add client side validation?而且效果很好,但是我还希望能够添加客户端验证?

In the custom validation attribute, implement the IClientModelValidator interface and create an AddValidation method.在自定义验证属性中,实现IClientModelValidator接口并创建AddValidation方法。 In the AddValidation method, add data- attributes for validation as follows:AddValidation方法中,添加data-属性进行验证,如下所示:

public class UniqueTitleAttribute : ValidationAttribute, IClientModelValidator
{
    protected override ValidationResult IsValid(
       object value, ValidationContext validationContext)
    {
        var context = (ApplicationDbContext)validationContext.GetService(typeof(ApplicationDbContext));
        var entity = context.Articles.SingleOrDefault(e => e.Title == value.ToString());

        if (entity != null)
        {
            return new ValidationResult(GetErrorMessage(value.ToString()));
        }
        return ValidationResult.Success;
    }

    public void AddValidation(ClientModelValidationContext context)
    {
        Type obj = typeof(Article);
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        MergeAttribute(context.Attributes, "data-val", "true");
        MergeAttribute(context.Attributes, "data-val-uniquetitle", GetErrorMessage());
    }
    private bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
    {
        if (attributes.ContainsKey(key))
        {
            return false;
        }

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

    public string GetErrorMessage()
    {
        return $"The title is already in use.";
    }
    public string GetErrorMessage(string title)
    {
        return $"Title {title} is already in use.";
    }
}

Add a method to jQuery validation library.向 jQuery 验证库添加方法。 It uses addMethod() method to specify our own validation function.它使用addMethod()方法来指定我们自己的验证 function。 The validation function receives the value entered in the title textbox.验证 function 接收在标题文本框中输入的值。 It then performs the validation and returns a boolean value.然后它执行验证并返回 boolean 值。

<div class="row">
<div class="col-md-4">
    <form method="post" asp-action="CreateArticle">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>

        <div class="form-group">
            <label asp-for="Title" class="control-label"></label>
            <input asp-for="Title" class="form-control" />
            <span asp-validation-for="Title" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="Author" class="control-label"></label>
            <input asp-for="Author" class="form-control" />
            <span asp-validation-for="Author" class="text-danger"></span>
        </div>

        <div class="form-group">
            <input type="submit" value="Create" class="btn btn-primary" />
        </div>
    </form>
</div>
</div>

@section Scripts
{
   @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
  <script type="text/javascript">
    var titlelist = @Html.Raw(Json.Serialize(ViewBag.TitleList));
    $.validator.addMethod("uniquetitle",
    function (value, element, param) {

        if (titlelist.includes(value)) {
            return false;
        }
        else {
            return true;
        }
    });
    $.validator.unobtrusive.adapters.addBool("uniquetitle");
  </script>
}

Save the TitleList in ViewBag in the Get method of the view,in order to judge if the title is in use from js:在视图的Get方法中保存ViewBag中的TitleList,以便js判断标题是否在使用中:

public IActionResult CreateArticle()
    {
        ViewBag.TitleList = _context.Articles.Select(a => a.Title).ToList();
        return View();
    }

Result:结果: 在此处输入图像描述

You have to use jquery and unobtrusive client side validation so fetch those urls in 
your page.

Use like 
<label asp-for="Name"></label>
<input asp-for="Name"/>
<span asp-validation-for="Name"></span>

Here i have taken example of Name as validation will fire on Name property but you can 
change property on which you want.

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

相关问题 ASP.Net Core MVC - 自定义属性的客户端验证 - ASP.Net Core MVC - Client-side validation for custom attribute ASP.NET MVC客户端验证的自定义属性 - ASP.NET MVC client-side validation of custom attribute 如何在ASP.NET Core 2.0中的自定义验证属性中进行客户端验证? - How To Do Client-Side Validation In Custom Validation Attribute In ASP.NET Core 2.0? ASP.NET razor 页面上的自定义验证属性的核心客户端验证 - ASP.NET Core client side validation for custom validation attribute on razor page 自定义验证属性中的客户端验证 - asp.net mvc 4 - client-side validation in custom validation attribute - asp.net mvc 4 使用 IClientModelValidator 在 ASP.NET Core 中带有参数的自定义客户端验证属性 - Custom client side validation attribute with parameter in ASP.NET Core using IClientModelValidator ASP.NET MVC3 - 自定义验证属性 - &gt;客户端损坏 - ASP.NET MVC3 - Custom validation attribute -> Client-side broken 自定义客户端验证(属性)不会在MVC 4中触发 - The custom client-side validation(attribute) doesn't trigger in MVC 4 自定义客户端验证未在 ASP.NET 内核中触发 - Custom Client-Side Validation not triggering in ASP.NET Core ASP MVC:自定义验证属性 - ASP MVC: Custom Validation Attribute
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM