Home > Net >  How do I limit the WPF TextBox to a numerical value between 1-50
How do I limit the WPF TextBox to a numerical value between 1-50

Time:10-27

So I have a TextBox and I want to limit the input to a numerical value from 0 - 50, is this possible? I've looked at some Regex examples using the PreviewTextInput but that only validates one number at a time.

I've also tried utilizing the MaxLength property, but that didn't seem to do much.

CodePudding user response:

Using WPFToolkit you can use IntegerUpDown (it's an easy way)

If not Should be like this (using preview text input)

<TextBox Name="NumberTextBoxLimited" PreviewTextInput="NumberValidationTextBox"/>

And using regular expressions

using System.Text.RegularExpressions;
private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
{
    e.Handled = new Regex(@"^(0?\d|[1-4]\d|50)$").IsMatch(e.Text);
}

CodePudding user response:

Consider treating this as a validation issue.

For instance, you could create a rule that inherits from ValidationRule that contains your custom validation logic.

public class NumberValidationRule : ValidationRule
{
  public override ValidationResult Validate(object value, CultureInfo cultureInfo)
  {
    int number;
    if (!int.TryParse(value.ToString(), out number))
    {
      return new ValidationResult(false, "Not a number");
    }
    
    if (number < 0 || number > 50) 
    {
      return new ValidationResult(false, "Not between 0 and 50.");
    }

    return new ValidationResult(true, null);
}

Then in your binding you'd add a the rule (like the snippet below for your TextBox). I omitted some extraneous Xaml for brevity.

<TextBox.Text>
  <Binding ...>
    <Binding.ValidationRules>
      <local:NumberValidationRule ValidationStep="RawProposedValue" />
    </Binding.ValidationRules>
  </Binding>
</TextBox.Text>

Another way would be to implement IDataErrorInfo on the model and put the validation logic there. You'd have to change the UpdateSourceTrigger to include ValidatesOnDataError=True as well.

  • Related