数据验证方法补充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>
相关推荐
追逐时光者8 分钟前
让 GitHub Copilot 更懂你的 .NET 代码风格:一份精简实用的 Copilot Instructions
后端·.net
Jeff-Tsai21 分钟前
Day 13:Session 管理与生命周期
.net·架构设计·erp·definition-driven
Lorenzo56516 小时前
扫码点餐里的并发和断网:我在第一个全栈项目里做的几个决定
.net
1-1=01 天前
C# IO和序列化
c#·.net·.netcore
Jeff-Tsai1 天前
Day 12:定义与数据缓存的跨节点失效
.net·架构设计·erp·definition-driven
CSharp精选营1 天前
从控制台到「会动手」的 AI:用 Semantic Kernel 搭应用(小白教程)
c#·.net·ai agent·semantickernel·functioncalling
Jeff-Tsai2 天前
Day 11:数据访问层的连接、Transaction 与查询条件
.net·架构设计·erp·definition-driven
宝桥南山2 天前
.NET 11 - 尝试一下Blazor中的新特性SupplyParameterFromTempData
microsoft·微软·c#·asp.net·.net·.netcore