增加模型验证接口实现验证方式

This commit is contained in:
falcon 2023-03-13 15:01:53 +08:00
parent 2a9928c209
commit 96beff6a1c
4 changed files with 55 additions and 2 deletions

View File

@ -0,0 +1,7 @@
namespace Falcon.SugarApi.ModelValidation
{
/// <summary>
/// 标记接口。表示该对象需要进行模型验证
/// </summary>
public interface IModelValidate { }
}

View File

@ -0,0 +1,19 @@
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Falcon.SugarApi.ModelValidation
{
/// <summary>
/// 对模型进行验证
/// </summary>
public static class IModelValidateResult
{
/// <summary>
/// 验证对象是否通过模型验证
/// </summary>
/// <param name="model">要验证的对象</param>
/// <returns>如果为null则通过否则返回验证结果列表</returns>
public static List<ValidationResult>? Validate(this IModelValidate model)
=> model.TryModelValidation(out var results) ? null : results;
}
}

View File

@ -14,10 +14,10 @@ namespace Falcon.SugarApi.ModelValidation
/// <param name="model">要验证的模型</param>
/// <param name="results">验证结果</param>
/// <returns>通过验证True否则False</returns>
public static bool TryModelValidation(this object model, out List<ValidationResult> results) {
public static bool TryModelValidation(this object model,out List<ValidationResult> results) {
var context = new ValidationContext(model);
results = new List<ValidationResult>();
return Validator.TryValidateObject(model, context, results, true);
return Validator.TryValidateObject(model,context,results,true);
}
}
}

View File

@ -0,0 +1,27 @@
## 数据模型验证
### 验证方式一直接调用TryModelValidation方法。
~~~C#
if(!data.TryModelValidation(out var errors)) {
//验证失败
}
//验证通过
~~~
### 验证方式二要验证的模型实现IModelValidate接口该接口为标记性接口无需任何实现。然后调用接口的Validate方法获取验证结果。
~~~C#
public class Model:IModelValidate{}
var data=new Model();
var errors=data.Validate();
if(errors!=null){
//验证失败
}
//验证通过
~~~