Xaml
<Grid>
<StackPanel Margin="0 20">
<WrapPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock Text="用户名" VerticalAlignment="Center"/>
<TextBox Margin="5 0" x:Name="TextBoxUserName" Width="200" Height="40"/>
</WrapPanel>
<WrapPanel Margin="0 20" HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock Text="住址" VerticalAlignment="Center"/>
<TextBox Margin="5 0" x:Name="TextBoxAddress" Width="200" Height="40"/>
</WrapPanel>
<Button x:Name="BtnSubmit" Margin="0 20" Width="110" Height="40" Click="BtnSubmit_Click" Content="Submit"/>
</StackPanel>
</Grid>
Validation Entity
public class Users {
public string UserName { get; set; }
public string Address { get; set; }
}
Validation Class
public class UserValidator: AbstractValidator<Users>
{
public UserValidator() {
RuleFor(user => user.UserName).NotEmpty().WithMessage("用户名不能为空");
RuleFor(user => user.Address).Length(10, 120).WithMessage("住址长度10~120字符");
}
}
Xaml.cs
private void BtnSubmit_Click(object sender, RoutedEventArgs e)
{
Users userEntity = new Users();
UserValidator validations = new UserValidator();
userEntity.UserName = TextBoxUserName.Text;
userEntity.Address = TextBoxAddress.Text;
ValidationResult validationResult = validations.Validate(userEntity);
if (!validationResult.IsValid)
{
MessageBox.Show(validationResult.ToString());
}
}
正则表达式验证
RuleFor(user => user.Id).Matches("^(\\d)+#34;);
自定义方法验证
RuleFor(user => user.Id).Must(Id => IsNumeric(Id.ToString())).WithMessage("Id是整型数字");
private bool IsNumeric(string value)
{
var digit = new Regex("(\\d)+");
return digit.IsMatch(value);
}
验证方法集合(共83个)
IsInEnum
ScalePrecision
ScalePrecision
PrecisionScale
PrecisionScale
Custom
CustomAsync
ForEach
IsEnumName
ChildRules
SetInheritanceValidator
Validate
ValidateAsync
ValidateAndThrow
ValidateAndThrowAsync
SetValidator
SetAsyncValidator
NotNull
Null
NotEmpty
Empty
Length
Length
Length
Length
Matches
MaximumLength
MinimumLength
Matches
Matches
Matches
Matches
Matches
EmailAddress
NotEqual
NotEqual
NotEqual
NotEqual
Equal
Equal
Equal
Equal
Must
Must
Must
MustAsync
MustAsync
MustAsync
LessThan
LessThan
LessThanOrEqualTo
LessThanOrEqualTo
GreaterThan
GreaterThan
GreaterThanOrEqualTo
GreaterThanOrEqualTo
LessThan
LessThan
LessThan
LessThan
LessThanOrEqualTo
LessThanOrEqualTo
LessThanOrEqualTo
LessThanOrEqualTo
GreaterThan
GreaterThan
GreaterThan
GreaterThan
GreaterThanOrEqualTo
GreaterThanOrEqualTo
GreaterThanOrEqualTo
GreaterThanOrEqualTo
InclusiveBetween
InclusiveBetween
InclusiveBetween
ExclusiveBetween
ExclusiveBetween
ExclusiveBetween
CreditCard
GetType
ToString
Equals
GetHashCode
静态效果
本文暂时没有评论,来添加一个吧(●'◡'●)