N
N
Nastya06962016-06-12 21:57:56
WPF
Nastya0696, 2016-06-12 21:57:56

Validation in wpf?

How to make it so that you can't enter numbers in a textbox

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sanostee, 2016-06-13
@andrewpianykh

Handle the TextChanged event like so:

private void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
  var index = textBox.CaretIndex;
  textBox.Text = Regex.Replace(textBox.Text, @"\d", "");
  textBox.CaretIndex = index;	
}

W
WarFollowsMe, 2016-06-20
@WarFollowsMe

public class OnlyTextValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        bool noNumbers = Regex.Matches("^([^0-9]*)$",value.ToString()).Count > 0;
        return new ValidationResult(noNumbers, "Value contains numbers");
    }
}

<Window.Resources>
    <local:OnlyTextValidationRule x:Key="NoNumberValidate"/>
</Window.Resources>

<TextBox Text={Binding Value, ValidationRules={StaticResource NoNumberValidate}}/>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question