Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restricting characters in a TextBox

I'm building a form in a C# WinRT app, and I'd like to restrict the characters in one of the TextBox components to numerals only. (This TextBox would be for a user to enter a year into.)

I've searched for a while, but haven't been able to figure this one out without setting up an event listener on the TextChanged event, and inspecting the text property on every key press. Is there a way to simply say that a user can only enter specific characters into a TextBox?

like image 641
Josh Buhler Avatar asked Apr 20 '12 01:04

Josh Buhler


People also ask

How do I restrict characters in textarea?

Note − By default, we can enter data in a textarea upto 5,24,288 characters. In some cases, there is a need of putting a limit on the size of characters that can be typed in a textarea. So in that case, we can use maxlength attribute to control the number of characters entered in a textarea.

How do I restrict characters in a text box in asp net?

Use the MaxLength property to limit the number of characters that can be entered in the TextBox control. This property is applicable only when the TextMode property is set to TextBoxMode. SingleLine or TextBoxMode. Password .

What is the limit of characters in text field type?

How To: Use the Text Field. The Text field is one of the most generic and common data entry fields used to capture text type data—letters, numbers, and symbols. Text fields hold up to 255 characters in a single line.


2 Answers

The simplest thing that could possibly work is to bind to the OnTextChanged event and modify the text according to your rules.

    <TextBox x:Name="TheText" TextChanged="OnTextChanged" MaxLength="4"/>
    private void OnTextChanged(object sender, TextChangedEventArgs e)
    {
        if (TheText.Text.Length == 0) return;

        var text = TheText.Text;

        int result;
        var isValid = int.TryParse(text, out result);
        if (isValid) return;

        TheText.Text = text.Remove(text.Length - 1);
        TheText.SelectionStart = text.Length;
    }

However, I'd shy away from this approach since the mantra of Metro is touch first UI and you can easy do it in a touch first manner with a FlipView control.

like image 58
Ritch Melton Avatar answered Sep 27 '22 17:09

Ritch Melton


Try setting TextBox.InputScope property to InputScopeNameValue.Number, as mentioned in Guidelines and checklist for text input in MSDN.

like image 36
sdb Avatar answered Sep 27 '22 17:09

sdb