数据验证方法补充ValidationRule

引言

除了使用CommunityToolkit.Mvvm工具包的ObservableValidator,.Net 抽象类VlidationRule也可以让我们实现自定义验证方法,但验证很受限,只能对当前值进行判断,无法获取对象的上下文。

ValidationRule

功能:验证值是否在0~100之间。

cs 复制代码
public class MyValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        double myValue = 0;
        if (double.TryParse(value.ToString(), out myValue))
        {
            if (myValue >= 0 && myValue <= 100)
                {
                    return new ValidationResult(true, null);
                }
        }
        return new ValidationResult(false, "Input should between 0 and 100");
    }
}

使用如下:

ValidationRules下面可以添加多个验证条件。

XML 复制代码
<TextBox Height="50" Margin="5,30,5,240" Name="tbx1" Validation.Error="tbx1_Error">
    <TextBox.Text>
          <Binding ElementName="slider" Path="Value" UpdateSourceTrigger="PropertyChanged" NotifyOnValidationError="True">
                <Binding.ValidationRules>
                      <hc:RegexRule Type = "Number"/>
                      <local:RangeValidationRule ValidatesOnTargetUpdated="True"/>
                </Binding.ValidationRules>
           </Binding>
    </TextBox.Text>
</TextBox>
相关推荐
IT规划师1 天前
Redis 数据类型全解 - List:用对是队列用错是灾难(二)
redis·消息队列·.net
1-1=01 天前
.NET Core 编译技术
.net·.netcore
1-1=02 天前
.NET Core 文件系统
.net·.netcore·1024程序员节
IsITGirl2 天前
VMware Fusion(Mac)Windows ARM 虚拟机 NAT (vmnet8) 报错解决记录
windows·macos·.net·桥接模式
学以智用3 天前
WinForms / WPF / Blazor 项目模板详解
.net
1-1=03 天前
.NET Core 内存管理
.net·.netcore
无风听海3 天前
.NET 10之Span技术总结
.net
1-1=03 天前
.NET Core 配置与选项
.net·.netcore·1024程序员节