
不用说,规则验证很重要,无效的参数,可能会导致程序的异常。
如果使用web api或mvc页面,那么可能习惯了自带的规则验证,我们的控制器很干净:
public class user
{
[required]
public string firstname { get; set; }
[required]
public string lastname { get; set; }
}
这种很常见,但是今天我想给你一个更好的替代方案:fluentvalidation, 通过这个库,您可以流畅地定义用于对象验证的复杂规则,从而轻松构建和理解验证规则,您可以在 github 上找到这个项目。
安装 fluentvalidation
我新建了一个很简单的.net core 的web api 程序,只有一个接口是用户注册,入参是一个user类, 然后在nuget中安装 fluentvalidation。
创建第一个验证
对于要验证的每个类,必须创建其自己的验证器,每个验证器类都必须继承abstractvalidator<t>,其中t是要验证的类,并且所有验证规则都在构造函数中定义。
最简单的验证是针对空值,如果要指定firstname和lastname都不能为空,这个验证器是这样:
public class uservalidator : abstractvalidator<user>
{
public uservalidator()
{
rulefor(x => x.firstname).notempty();
rulefor(x => x.lastname).notempty();
}
}
就这些了,您已经创建了第一个验证器,是不是超级简单!
还有一些其他的规则,比如 minimumlength,maximumlength和length,用于验证长度,您可以把多个规则指定到一个字段,就像这样:
public class uservalidator : abstractvalidator<user>
{
public uservalidator()
{
rulefor(x => x.firstname).notempty();
rulefor(x => x.firstname).minimumlength(3);
rulefor(x => x.firstname).maximumlength(20);
rulefor(x => x.lastname).notempty();
}
}
验证入参
我们之前已经定义了验证规则,现在开始使用它,您只需要new 一个uservalidator对象,然后调用validate方法, 它会返回一个对象,其中包含了验证状态和所有没有通过验证的信息。
[httppost]
public iactionresult register(user newuser)
{
var validator = new uservalidator();
var validationresult = validator.validate(newuser);
if (!validationresult.isvalid)
{
return badrequest(validationresult.errors.first().errormessage);
}
return ok();
}
如果我运行程序,然后输入一个超长的名字:
{
"firstname": "赵钱孙李周吴郑王冯陈褚卫蒋沈韩杨朱秦尤许何吕施张",
"lastname": "张"
}
我会收到验证错误:"the length of 'first name' must be 20 characters or fewer. you entered 24 characters"。
好吧,我不喜欢这个消息,那么你可以自定义错误消息,这很简单,您可以使用 withmessage 方法。
- rulefor(x => x.firstname).maximumlength(20);
+ rulefor(x => x.firstname).maximumlength(20).withmessage("您的名字长度已经超出了限制!");
流利验证
你可以把验证规则,改成下边这样:
- rulefor(x => x.firstname).notempty(); - rulefor(x => x.firstname).minimumlength(3); + rulefor(x => x.firstname).notempty().minimumlength(3);
然后也可以把验证规则应用于其他的属性,就像这样:
public uservalidator()
{
rulefor(x => x.firstname)
.maximumlength(20).withmessage("您的名字长度已经超出了限制!")
.notempty().minimumlength(3);
rulefor(x => x.lastname).notempty();
}
常见的验证规则
这个库有很多现成的基本类型验证规则, 对于字符串,您可以使用不同的方法,比如 emailaddress,isenumname(检查值是否在指定的enum类型中定义)和 inclusivebetween, 检查该值是否在定义的范围内。
现在,我在user类添加了另外两个字段,password 和 confirmpassword。
password字段是一个字符串,有效的长度必须在5到15个字符之间,并且要符合正则,为了定义是否满足安全规则,我定义了一个hasvalidpassword方法,它会返回一个bool值。
private bool hasvalidpassword(string pw)
{
var lowercase = new regex("[a-z]+");
var uppercase = new regex("[a-z]+");
var digit = new regex("(\\d)+");
var symbol = new regex("(\\w)+");
return (lowercase.ismatch(pw) && uppercase.ismatch(pw) && digit.ismatch(pw) && symbol.ismatch(pw));
}
然后在密码验证中使用:
rulefor(x => x.firstname)
.maximumlength(20).withmessage("您的名字长度已经超出了限制!")
.notempty().minimumlength(3);
rulefor(x => x.lastname).notempty();
rulefor(x => x.password)
.length(5, 15)
.must(x => hasvalidpassword(x));
还可以简化一些:
rulefor(x => x.password) .length(5, 15) - .must(x => hasvalidpassword(x)); + .must(hasvalidpassword); }
confirmpassword字段的唯一要求是等于password字段:
rulefor(x => x.confirmpassword)
.equal(x => x.password)
.withmessage("2次密码不一致!");
注入验证器
修改startup类中的configureservices方法:
public void configureservices(iservicecollection services)
{
services.addcontrollers().addfluentvalidation();
services.addtransient<ivalidator<user>, uservalidator>();
}
注意:这个地方的生命周期是 transient。
这样,在调用注册接口的时候,会自动进行规则验证:
[httppost]
public iactionresult register(user newuser)
{
return ok();
}
然后,我们再尝试传入参数来调用接口:
{
"firstname": "赵钱孙李周吴郑王冯陈褚卫蒋沈韩杨朱秦尤许何吕施张",
"lastname": "张"
}
很明显,验证不通过,接口会返回这样的错误信息:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "one or more validation errors occurred.",
"status": 400,
"traceid": "|c4523c02-4899b7f3df86a629.",
"errors": {
"firstname": [
"您的名字长度已经超出了限制!"
]
}
}
希望对您有帮助,您可以在官方文档中找到更多的用法。
原文链接: https://www.code4it.dev/blog/fluentvalidation
到此这篇关于在.net core 中使用 fluentvalidation 进行规则验证的文章就介绍到这了,更多相关.net core 规则验证内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论