randoms
randoms

Reputation: 2783

Input Validation Silverlight

i have a textbox which is not bound.

<TextBox x:Name="inputBox" Grid.Column="1" Grid.Row="1"  />

The textbox is to only accept numbers (doubles) and show a warning at once something else(letters or symbols) is written in to the box.

On the TextChanged event, i do some calculations depending on the value enterd and show it in a TextBlock, therefor i need some way of validating that the input is a number as the user writes in the box, but i am having a hard time finding a good way to do this.

Any ideas?

Upvotes: 2

Views: 2063

Answers (3)

Bryant
Bryant

Reputation: 8670

This is another example of when to use a Behavior.

public class TextBoxValidator : Behavior<TextBox>
{
  protected override void OnAttached()
  {
    AssociatedObject.TextChanged += new TextChanged(OnTextChanged);
  }

  private void OnTextChanged(object sender, TextChangedEventArgs e)
  {
    // Here you could add the code shown above by Firedragon or you could
    // just use int.TryParse to see if the number if valid.
    // You could also expose a Regex property on the behavior to allow lots of
    // types of validation
  }
}

You didn't really explain what actions you wanted to take when the user enters an invalid value.

Upvotes: 2

Anatolii Gabuza
Anatolii Gabuza

Reputation: 6260

Maybe it would be better to use Binding with ValueConverter that will update TextBlock's content. In this case you can implement validation for numeric value in within converter.

Upvotes: 1

Firedragon
Firedragon

Reputation: 3733

What I have used before is a regex to disallow non-numeric characters. Maybe this is something that could be adapted?

My code was for a port on a server so only numbers but should be straightforward to add the . for doubles (I think "[^0-9\.]" should work but regexs aren't something I am fantastically good at :-) )

// Text change in Port text box
private void txtPort_TextChanged(object sender, TextChangedEventArgs e)
{
    // Only allow numeric input into the Port setting.
    Regex rxAllowed = new Regex(@"[^0-9]", RegexOptions.IgnoreCase);

    txtPort.Text = rxAllowed.Replace(txtPort.Text, ""); 
    txtPort.SelectionStart = txtPort.Text.Length; 
}

Upvotes: 4

Related Questions