我有自定义验证比较模型中的两个值。服务器端验证运行正常。
但是,我想知道我需要添加什么才能使自定义模型验证在客户端工作(即在按下提交按钮之前显示红色的小错误消息)。现在我的红色小错误消息仅在按下提交按钮后出现。
相关代码的简化版本如下:
在viewmodel.cs
文件中:
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Collections.Generic;
public class MyViewModel : IValidatableObject
{
public int value1 { get; set; }
[Range(0, 1000, ErrorMessage = "Must be a positive integer between 0 and 1000")]
public int value2 { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (value2 > value1)
yield return new ValidationResult("value2 cannot be more than value1).", new List<string> { "value1" });
}
}
在 cshtml 视图中:
<input asp-for="value1" />
<p style="color:red"><span asp-validation-for="value1"></span> </p>
<input asp-for="value2" />
<p style="color:red"><span asp-validation-for="value2"></span> </p>
发布表单时,我检查控制器内的“ModelState.IsValid”。
包括“jquery.validate.min.js”和“jquery.validate.unobtrusive.min.js”(客户端范围验证工作正常,所以我知道 jquery 库设置正确)。