我正在学习自定义验证属性,并为自己创建了一个简单的示例,但它似乎不起作用。我错过了什么?
这是我的模型
public class Employee
{
public int? ID { get; set; }
[MinLength(2)] [Remote(action: "VerifyNameExists",controller:"Employee")]
public string Name { get; set; }
[LastNameValid] public string? lastname { get; set; }
public decimal? Salary { get; set; }
}
字符串
这是我的观点
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation/dist/additional-methods.min.js"></script>
<script src="~/lib/jquery-validation/dist/additional-methods.js"></script>
<a href="~/lib/jquery/dist/jquery.min.map">~/lib/jquery/dist/jquery.min.map</a>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery/dist/jquery.js"></script>
@model Employee
<div class="container">
<h1>Create Employee</h1>
<div class="row">
<div class="col-sm-8">
<form class="d-grid form-control-sm" asp-controller="Employee" asp-action="Create" method="post">
<div class="form-group row">
<input class="col-sm-4" asp-for="ID" placeholder="ID" />
<span asp-validation-for="ID" style="color:red"></span>
</div>
<br />
<div class="form-group row">
<input type="text" class="col-sm-4" asp-for="Name" placeholder="First Name"/>
<span asp-validation-for="Name" style="color:red"></span>
</div>
<br />
<div class="form-group row">
<input type="text" class="col-sm-4" asp-for=lastname placeholder="Last Name"/>
<span asp-validation-for=lastname style="color:red"></span>
</div>
<br />
<br/>
<input class="btn btn-primary col-sm-4" type="submit" name="Submit" value="Submit" />
</form>
</div>
</div>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial"></partial>
}
型
这是我的控制器
public IActionResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create(Employee emp)
{
if (!ModelState.IsValid)
{
return View();
}
return RedirectToAction("Index",emplist);
}
型
下面是添加到模型的last name属性的属性类:
using System.ComponentModel.DataAnnotations;
namespace MVCDemo
{
public class LastNameValidAttribute : ValidationAttribute
{
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
if (value == "abc")
{
return new ValidationResult("not allowed");
}
return ValidationResult.Success;
}
}
}
型
我读了这个网站上的其他问题,我不认为我在这里做什么不同。
当我提交表单时,没有根据属性验证姓氏
1条答案
按热度按时间yfwxisqw1#
对于服务器,你可以在
if (value == "abc")
设置一个断点,你可以看到它为false,试试value.ToString() == "abc"
:字符串
结果:
的数据
对于需要添加js的Client,可以阅读自定义客户端验证了解更多。
下面是一个demo,你可以参考一下:
LastNameValidAttribute:
型
修改js如下:
型
结果: