0%

【FluentValidation】與MVC 5綁定Model Validation

MVC很早就提供Model Validation的驗證方式,只要在Parameter Class的Property加上限制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Movie {
[Required]
public int ID { get; set; }

[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }

[Range(1, 100)]
[DataType(DataType.Currency)]
public decimal Price { get; set; }

[StringLength(5)]
public string Rating { get; set; }
}

接著在Action之中使用ModelState.IsValid即可驗證參數是否符合規定

1
2
3
4
5
6
7
8
9
10
11
12
13
[HttpPost]
public ActionResult Create(Movie movie)
{
if (ModelState.IsValid)
{
db.Movies.Add(movie);
db.SaveChanges();
return RedirectToAction("Index");
}

return View(movie);
}

最近比較習慣使用FluentValidation,剛好它也在MVC5上設定一下,就可以用ModelState.IsValid來得知參數驗證是否成功,以下紀錄實作方法

1.首先在MVC專案中安裝FluentValidation.MVC5

[![](https://2.bp.blogspot.com/-OYlSu6hpFFQ/WNsigw1fSyI/AAAAAAAAIF4/pO02UtoeK5g1ipJT0T6Z6JLb_8a5PkjCwCLcB/s1600/1.png)](https://2.bp.blogspot.com/-OYlSu6hpFFQ/WNsigw1fSyI/AAAAAAAAIF4/pO02UtoeK5g1ipJT0T6Z6JLb_8a5PkjCwCLcB/s1600/1.png)
2.接著在Global  Application_Start加上
1
2
FluentValidationModelValidatorProvider.Configure();

3.準備一個要驗證的參數類別

1
2
3
4
5
6
7
public class WantValidateParameter
{
public string ID { get; set; }

public string Name { get; set; }
}

4.跟前幾天提到的文章一樣,寫對應的驗證方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class ParameterValidator :AbstractValidator<WantValidateParameter>
{
public ParameterValidator()
{
this.RuleFor(x => x.ID)
.NotNull()
.WithErrorCode("400")
.WithMessage("ID不能為Null")
.NotEmpty()
.WithErrorCode("400")
.WithMessage("ID不能為空字串");

this.RuleFor(x => x.Name)
.NotNull()
.WithErrorCode("401")
.WithMessage("Name不能為Null")
.NotEmpty()
.WithErrorCode("401")
.WithMessage("Name不能為空字串")
.Length(4, 6)
.WithErrorCode("401")
.WithMessage("Name必須在4~6字之間");
}
}

5.接著在剛剛要驗證的參數類別上加上Attribute

1
2
3
4
5
6
7
8
[Validator(typeof(ParameterValidator))]
public class WantValidateParameter
{
public string ID { get; set; }

public string Name { get; set; }
}

6.在Action裡面就可以用ModelState.IsValid來得知參數是否驗證成功啦!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public ActionResult Test(WantValidateParameter parameter)
{
string Result = string.Empty;
if (!ModelState.IsValid)
{
//取得錯誤的訊息
var Error = ModelState.Values.SelectMany(x => x.Errors).FirstOrDefault();
Result = Error.ErrorMessage;
}
else
{
Result = "驗證成功";
}

return View(model: Result);
}

參考文章 :
1.https://github.com/JeremySkinner/FluentValidation/wiki/h.-MVC
2.MSDN : Adding Validation to the Model