0

How can I validate one Textbox so that it only contains ASCII characters?

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

I tried to add a ValidationRule, but it needs always to implement Min and Max properties

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;
    }
}
miguelmpn
  • 1,859
  • 1
  • 19
  • 25

1 Answers1

1

Checking if a character is an ASCII-character is quite easy actually.

It looks like you took the code from the example class in the .NET docs page. The class there is for validating an age range, so it's going to need the Min and Max properties, but you don't need them and a validation rule certaintly doesn't always need to implement them, so you can safely remove them.

The validation rule can look something like this (C# 7 or later):

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

The ch < 128 part is the ASCII check.

You also need to specify that you want to use the rule in your binding (supposing that your rule lives in the c XAML namespace).

<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>

You can find more information on data binding validation in the docs.

Tolik Pylypchuk
  • 680
  • 1
  • 6
  • 15