实验14——自定义服务器端验证
1. 创建自定义验证
新建类,并命名为FirstNameValidation,代码如下:
1: public class FirstNameValidation:ValidationAttribute
2: {
3: protected override ValidationResult IsValid(object value, ValidationContext validationContext)
4: {
5: if (value == null) // Checking for Empty Value
6: {
7: return new ValidationResult("Please Provide First Name");
8: }
9: else
10: {
11: if (value.ToString().Contains("@"))
12: {
13: return new ValidationResult("First Name should contain @");
14: }
15: }
16: return ValidationResult.Success;
17: }
18: }
2. 附加到First Name
打开Employee类,删除FirstName的默认的Required属性,添加FirstNameValidation,代码如下:
1: [FirstNameValidation]
2: public string FirstName { get; set; }
3. 运行
导航到Employee/AddNew
测试1:
测试2:
结论
本节主要讲解了数据访问层相关的知识,如数据验证,数据更新,数据处理,form表单的使用等。
public class FirstNameValidation:ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null) // Checking for Empty Value
{
return new ValidationResult("Please Provide First Name");
}
else
{
if (value.ToString().Contains("@"))
{
return new ValidationResult("First Name should not contain @");
}
}
return ValidationResult.Success;
}
}
public class Employee
{
[Key]
public int EmployeeId { get; set; }
[FirstNameValidation]
public string FirstName { get; set; }
[StringLength(5,ErrorMessage="Last Name length should not be greater than 5")]
public string LastName { get; set; }
[Required(ErrorMessage = "the Salary field is required!")]
public int Salary { get; set; }
}