【问题标题】:Validation Rule for checking if text has only ASCII检查文本是否只有 ASCII 的验证规则
【发布时间】:2020-03-02 04:25:07
【问题描述】:

如何验证一个文本框以使其仅包含 ASCII 字符?

<TextBox Name="PbnameText" Visibility="Collapsed" IsReadOnly="False" Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

我尝试添加一个 ValidationRule,但它总是需要实现 Min 和 Max 属性

public class NameRule : ValidationRule
{
    public int Min { get; set; }
    public int Max { get; set; }

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        if (true)
            return new ValidationResult(false, $"Illegal characters or {e.Message}");
        else
            return ValidationResult.ValidResult;
    }
}

【问题讨论】:

    标签: c# wpf validation xaml ascii


    【解决方案1】:

    检查字符是否为 ASCII 字符实际上是 quite easy

    看起来您从.NET docs page 中的示例类中获取了代码。该类用于验证年龄范围,因此需要 MinMax 属性,但您不需要它们,并且验证规则肯定不需要总是实施它们,以便您可以安全地删除它们。

    验证规则可能如下所示(C# 7 或更高版本):

    using System.Globalization;
    using System.Linq;
    using System.Windows.Controls;
    
    public class NameRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            return value is string str && str.All(ch => ch < 128)
                ? ValidationResult.ValidResult
                : new ValidationResult(false, "The name contains illegal characters");
        }
    }
    

    ch &lt; 128 部分是 ASCII 检查。

    您还需要指定要在绑定中使用该规则(假设您的规则位于 c XAML 命名空间中)。

    <TextBox Name="PbnameText" Visibility="Collapsed" IsReadOnly="False">
        <TextBox.Text>
            <Binding Path="Name" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
                <Binding.ValidationRules>
                    <c:NameRule />
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>
    

    您可以找到更多关于数据绑定验证的信息in the docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-20
      • 2020-11-30
      • 2015-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-11
      相关资源
      最近更新 更多