C# WPF 使用FluentValidation實現數據有效性效驗

2024年2月6日 15点热度 0人点赞

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) $");

自定義方法驗證

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

靜態效果