[英]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();
}
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.