Visual
自定义验证 Attribute —>继承自IModelValidator
- Attribute,IModelValidator
示例:ValidUrlAttribute
public class ValidUrlAttribute : Attribute, IModelValidator
{
public string ErrorMessage { get; set; }
public IEnumerable<ModelValidationResult> Validate(
ModelValidationContext context)
{
var url = context.Model as string;
if (url != null && Uri.IsWellFormedUriString(url, UriKind.Absolute))
{
return Enumerable.Empty<ModelValidationResult>();
}
return new List<ModelValidationResult>
{
new ModelValidationResult(string.Empty, ErrorMessage)
};
}
}
使用时标注在 ViewModel 等实体类的属性上即可:
[Display(Name = "封面地址")]
[Required(ErrorMessage = "{0}是必填项"), MaxLength(200, ErrorMessage = "{0}的长度不可超过{1}")]
//[DataType(DataType.Url)]
[ValidUrl(ErrorMessage = "这个URL不正确")]
public string CoverUrl { get; set; }
远程验证
- [Remote]
- 客户端调用 Action 方法进行验证(前台调用后台验证)
Action 中的方法:
[AcceptVerbs("Get", "Post")]
public async Task<IActionResult> CheckRoleExist([Bind("RoleName")]string roleName)
{
var role = await _roleManager.FindByNameAsync(roleName);
if (role != null) return Json("角色已经存在了");
return Json(true);
}
标注属性:
public class RoleAddViewModel
{
[Required]
[Display(Name = "角色名称")]
///[Remote("CheckRoleExist", "RoleController", ErrorMessage = "角色已存在")]
[Remote(nameof(RoleController.CheckRoleExist), "Role", ErrorMessage = "角色已存在")]
public string RoleName { get; set; }
}
注:暂时没找到更优雅的方法获取到 “Role”。