增加模型验证接口实现验证方式
This commit is contained in:
parent
2a9928c209
commit
96beff6a1c
7
Falcon.SugarApi/ModelValidation/IModelValidate.cs
Normal file
7
Falcon.SugarApi/ModelValidation/IModelValidate.cs
Normal file
|
@ -0,0 +1,7 @@
|
||||||
|
namespace Falcon.SugarApi.ModelValidation
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 标记接口。表示该对象需要进行模型验证
|
||||||
|
/// </summary>
|
||||||
|
public interface IModelValidate { }
|
||||||
|
}
|
19
Falcon.SugarApi/ModelValidation/IModelValidateResult.cs
Normal file
19
Falcon.SugarApi/ModelValidation/IModelValidateResult.cs
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
27
Falcon.SugarApi/ModelValidation/Readme.md
Normal file
27
Falcon.SugarApi/ModelValidation/Readme.md
Normal 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){
|
||||||
|
//验证失败
|
||||||
|
}
|
||||||
|
//验证通过
|
||||||
|
|
||||||
|
~~~
|
Loading…
Reference in New Issue
Block a user