我正在使用mvc。所以我想验证用户输入的数字是7位数。
所以我写了一堂课。
public class StduentValidator : AbstractValidator<graduandModel>
{
public StduentValidator(ILocalizationService localizationService)
{
RuleFor(x => x.student_id).Equal(7)
.WithMessage(localizationService
.GetResource("Hire.graduand.Fields.student_id.Required"));
}
但它不起作用。 如何验证7位数字?
答案 0 :(得分:17)
由于您正在使用FluentValidation,因此您希望使用.Matches验证程序来执行正则表达式匹配。
RuleFor(x => x.student_id).Matches("^\d{7}$")....
另一种选择是做这样的事情(如果student_id是一个数字):
RuleFor(x => x.student_id).Must(x => x > 999999 && x < 10000000)...
或者,您可以使用GreaterThan和LessThan验证器,但上面更容易阅读。另请注意,如果数字类似于0000001,那么上述内容将不起作用,您必须将其转换为7位数的字符串并使用以下技术。
如果student_id是一个字符串,那么这样的话:
int i = 0;
RuleFor(x => x.student_id).Length(7,7).Must(x => int.TryParse(x, out i))...
答案 1 :(得分:1)
您可以{/ 1}}使用
Regex
答案 2 :(得分:0)
您可以使用必须扩展名。并将值转换为字符串,以便您可以使用 .Length
RuleFor(x => x.student_id).Must(x => x.ToString().Length == 7)