1. 添加引用:
System.ComponentModel.DataAnnotations.dll
2. 拿登陆验证参数为例:创建模型LoginUser;
1)在需要验证的字段上边添加特性,如
[Required(ErrorMessage ="用户名不允许为空")]
2)继承IValidatableObject 是为了重写Validate,实现在某种条件下触发验证code不为空。
public class LoginUser : IValidatableObject
{
[Required(ErrorMessage ="用户名不允许为空")]
public string username { get; set; }
[Required(ErrorMessage ="密码不允许为空")]
[StringLength(10, ErrorMessage = "字符长度过长")]
public string password { get; set; }
public string code { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
LoginUser userModel = validationContext.ObjectInstance as LoginUser;
if (userModel==null)
{
yield break;
}
bool isValidCode= true;
if (isValidCode && string.IsNullOrWhiteSpace(code))
{
yield return new ValidationResult("验证码不允许为空", new string[] { code });
}
}
}
3. 接下来就是验证;
1)增加辅助验证类
public static class ValidatetionHelper
{
public static ValidResult IsValid(object value)
{
ValidResult result = new ValidResult();
try
{
var validationContext = new ValidationContext(value);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(value, validationContext, results, true);
if (!isValid)
{
result.IsVaild = false;
result.ErrorMembers = new List<ErrorMember>();
foreach (var item in results)
{
result.ErrorMembers.Add(new ErrorMember()
{
ErrorMessage = item.ErrorMessage,
ErrorMemberName = item.MemberNames.FirstOrDefault()
});
}
}
else
{
result.IsVaild = true;
}
}
catch (Exception ex)
{
result.IsVaild = false;
result.ErrorMembers = new List<ErrorMember>();
result.ErrorMembers.Add(new ErrorMember()
{
ErrorMessage = ex.Message,
ErrorMemberName = "Internal error"
});
}
return result;
}
public class ValidResult
{
public List<ErrorMember> ErrorMembers { get; set; }
public bool IsVaild { get; set; }
}
public class ErrorMember
{
public string ErrorMessage { get; set; }
public string ErrorMemberName { get; set; }
}
}
2)使用验证类进行验证
public ActionResult Login(LoginUser user)
{
//验证参数
var result = ValidatetionHelper.IsValid(user);
if (!result.IsVaild)
{
return JsonMsg(false, result.ErrorMembers.FirstOrDefault().ErrorMessage);
}
//验证登陆
//...
}
到此,验证参数如何使用已经演示完毕!除了不为空还有其他的特性可以查阅资料或自己重写。