验证 Valid
自定义验证特性
1 using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; 2 3 namespace MvcMovie.Validations 4 { 5 /// <summary> 6 /// 自定义验证Url特性 7 /// </summary> 8 public class ValidUrlAttribute : Attribute, IModelValidator 9 { 10 public string ErrorMessage { get; set; } = "无效的Url"; 11 public ValidUrlAttribute() 12 { 13 14 } 15 public ValidUrlAttribute(string errorMessage) 16 { 17 ErrorMessage = errorMessage; 18 } 19 public IEnumerable<ModelValidationResult> Validate(ModelValidationContext context) 20 { 21 var url = context.Model as string; 22 if (url != null && Uri.IsWellFormedUriString(url, UriKind.Absolute)) 23 { 24 return Enumerable.Empty<ModelValidationResult>(); 25 } 26 return new List<ModelValidationResult> 27 { 28 new ModelValidationResult(string.Empty,ErrorMessage) 29 }; 30 } 31 } 32 }
Model模型使用:
[ValidUrl(ErrorMessage ="Url不正确")] public string? ConverUrl { get; set; }
效果:
远程验证 Remote
客户端调用 Action 方法进行验证
Model 模型添加远程验证特性
[Remote(nameof(UserController.CheckUserExist), "User",ErrorMessage ="用户已存在")] public string UserName { get; set; }
在 UserController 控件器中定义远程验证类:
[AcceptVerbs("Get", "Post")] public async Task<IActionResult> CheckUserExist([Bind(nameof(UserCreateViewModel.UserName))] string userName) { var user = await m_UserManager.Users.FirstOrDefaultAsync(x => x.UserName == userName); if (user == null) { return Json(true); } else { return Json("用户已经存在"); } }
注意:必须在 View 底部添加脚本
@section Scripts { @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } }