校验字段格式
BaseController方法:
public static StringBuilder GetErrorMsg(ModelStateDictionary modelState) { StringBuilder builder = new StringBuilder(); foreach (var item in modelState.Values) { if (item.Errors.Count > 0) { builder.Append(item.Errors[0].ErrorMessage); } } return builder; }
EmployeeController:
var json = new JsonHelper() { Status = "n" }; if (!ModelState.IsValid) { builder = GetErrorMsg(ModelState); } if (string.IsNullOrEmpty(employeeDto.EmployeeID)) { // 新增校验是否已存在该身份证的员工 if (_employeeService.IsExist(e => e.IDCard == employeeDto.IDCard&&!e.IsDelete&&e.Status!=2)) { builder.AppendLine("员工信息已存在"); } } if (employeeDto.IDCardType == 1) { if (!Util.CheckIDCard(employeeDto.IDCard.Trim())) { builder.AppendLine("身份证号码填写有误"); } } if (builder.Length > 0) { json.Msg = builder.ToString(); return Json(json); }
可以在实体类中对定义的变量添加限制条件,如[Required]、[Range(1, 2)]、[RegularExpression(@"^(13[0-9]|14[579]|15[0-3,5-9]|17[0135678]|18[0-9]|16[6]|19[89])\d{8}$", ErrorMessage ="手机号码格式错误")]、
[RegularExpression(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage ="邮箱格式填写有误")]等。。