Input Restriction in WPF MaskedTextBox (SfMaskedEdit)

18 Nov 201820 minutes to read

This section explains how to use the WPF MaskedTextBox properties and events.

Restrict the user to enter valid data

You can restrict valid input without custom validation by creating a mask pattern. Enable the mask by setting the mask pattern to the Mask property and set the MaskType property to Regex. The default value of the Mask property is null, and the default value of the MaskType property is Simple. The following table describes the mask elements:

Elements Description
[] It denotes the set to define the particular input elements.
[ABC] Accepts any single character included in the specified set of characters.
[^ABC] Accepts any single character not included in the specified set of characters.
[A-Z] Accepts any character between two specified set of characters inclusive.
\d Accepts any digit. Same as [0-9].
\D Accepts any non-digit. Same as [^0-9].
\w Accepts any word character. \w is the same as [a-zA-Z_0-9].
\W Accepts any non-word character. \W is the same as [^a-zA-Z_0-9].
\s Accepts any white space characters.
\S Accepts any non-white space characters.
(?=subexpression) Matches a group after the main expression without including it in the result.
(?!subexpression) Specifies a group that cannot match after the main expression.
{n} Accepts the input n number of times.
{n,} Accepts the input 'n' or more number of times.
{n,m} Accepts the input a minimum of n times and a maximum of m times.
+ Accepts one or more matches for the preceding character.
* Accepts zero or more matches for the preceding character.
? Optional input (zero or one occurrence of the matching input).
| Acts like a Boolean OR. Matches the expression before or after the |.
. Accepts any character. It can be changed based on culture.

Allow specific values

If you want to allow the user to enter only the specific values, use the (?=subexpression) with the mask. It will match the input with the mask when value is same as the subexpression.

<syncfusion:SfMaskedEdit Mask="(?=123)\d{3}" 
                         MaskType = "RegEx"
                         Name="sfMaskedEdit"/>
SfMaskedEdit sfMaskedEdit = new SfMaskedEdit();
sfMaskedEdit.MaskType = MaskType.RegEx;
sfMaskedEdit.Mask = @"(?=123)\d{3}";

For the input mask (?=123)\d{3}, the control accepts only the value 123. While entering the digits, each input is validated against the regex and invalid input is restricted. The output is allowed only when the MaskText is 123.

WPF MaskedTextBox displays Specific Values with Mask

Restrict specific values

If you want to restrict the user to enter some specific values, use the (?!subexpression) with the mask. It will not allow the input when value is same as the subexpression.

<syncfusion:SfMaskedEdit Mask="(?!55)(?!000)(?!666)\d{3}" 
                         MaskType = "RegEx"
                         Name="sfMaskedEdit"/>
SfMaskedEdit sfMaskedEdit = new SfMaskedEdit();
sfMaskedEdit.MaskType = MaskType.RegEx;
sfMaskedEdit.Mask = @"(?!55)(?!000)(?!666)\d{3}";

For the input mask (?!55)(?!000)(?!666)\d{3} – \d{3} denotes that the output will be of 3 character length. (?!55) denotes the value cannot begin with 55. (?!000)(?!666) denotes the output cannot be 000 or 666.

Restrict Specific Values with Mask in WPF MaskedTextBox

Basic Mask examples

You can create your custom mask as follows,

Mask use case Pattern Example
Positive whole number \d+ WPF MaskedTextBox Positive whole number
Negative whole number -\d+ WPF MaskedTextBox Negative whole number
Positive and negative whole number -?\d+ WPF MaskedTextBox Whole number
Positive and negative float number -?\d+\.?\d* WPF MaskedTextBox Positive Negative
Percent value \d+\.\d{2}% WPF MaskedTextBox Percent
Currency value $ \d+\.\d{2}" WPF MaskedTextBox Currency
Alphanumeric with space [a-zA-Z0-9 ]* WPF MaskedTextBox Alphanumeric with space
Alphanumeric without space [a-zA-Z0-9]* WPF MaskedTextBox Alphanumeric without space
Email ID [A-Za-z0-9._%-]+@[A-Za-z0-9]+.[A-Za-z]{2,3} WPF MaskedTextBox Email
Hexadecimal number \\x[0-9A-Fa-f]{1,2} WPF MaskedTextBox Hexadecimal number
Octal number \\0[0-7]{1,3} WPF MaskedTextBox Octal number
Hexadecimal color code #[A-Fa-f0-9]{6} WPF MaskedTextBox Hexadecimal color code
Time (0[0-9]|1[0-9]|2[0-3]):[0-5][0-9] WPF MaskedTextBox Time
Phone number \([0-9]\d{2}\) [0-9]\d{2}-[0-9]\d{3} WPF MaskedTextBox AccountNumber
Product key [A-Z\d]{5}-[A-Z\d]{5}-[A-Z\d]{5}-[A-Z\d]{5}-[A-Z\d]{5} WPF MaskedTextBox Product key
Zip code \d{5}-\d{5} WPF MaskedTextBox Zip code
Bank SWIFT code [A-Z]{6}[0-9]{2}[A-Z]{3} WPF MaskedTextBox Bank SWIFT code
Bank Account Number \d{8,12} WPF MaskedTextBox AccountNumber
Credit Card Number \d{4} \d{4} \d{4} \d{4} WPF MaskedTextBox Credit Card Number

View Sample in GitHub

Setting the value

You can set the value for the SfMaskedEdit by using the Value property. Based on the mask, the value of the Value property is formatted. The default value of the Value property is null.

<syncfusion:SfMaskedEdit Value="4553456789"
                         Mask="\([0-9]\d{2}\) [0-9]\d{2}-[0-9]\d{3}" 
                         MaskType = "RegEx"
                         Name="sfMaskedEdit"/>
SfMaskedEdit sfMaskedEdit = new SfMaskedEdit();
sfMaskedEdit.Value="4553456789";
sfMaskedEdit.MaskType = MaskType.RegEx;
sfMaskedEdit.Mask = @"\([0-9]\d{2}\) [0-9]\d{2}-[0-9]\d{3}";

WPF MaskedTextBox displays Value without Prompt and Literals

View Sample in GitHub

Get the value in various formats

By default, the Value property holds your input characters, prompt characters, and the literals defined in the mask. You can modify this and allow the Value property to hold the characters without prompt and literals by setting the ValueMaskFormat property. The value can be formatted by any one of the following formatting options,

  • ExcludePromptAndLiterals
  • IncludeLiterals
  • IncludePrompt
  • IncludePromptAndLiterals

Value without prompt character and literals

If you want to get only the text entered by the user, use the ValueMaskFormat property as ExcludePromptAndLiterals. It does not include prompt and literal characters in the Value property.

<syncfusion:SfMaskedEdit ValueMaskFormat="ExcludePromptAndLiterals"
                         Mask="\([0-9]\d{2}\) [0-9]\d{2}-[0-9]\d{3}" 
                         MaskType = "RegEx"
                         Name="sfMaskedEdit"/>
SfMaskedEdit sfMaskedEdit = new SfMaskedEdit();
sfMaskedEdit.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals;
sfMaskedEdit.MaskType = MaskType.RegEx;
sfMaskedEdit.Mask = @"\([0-9]\d{2}\) [0-9]\d{2}-[0-9]\d{3}";

WPF MaskedTextBox displays Value in Various Formats

View Sample in GitHub

Value with literals

If you want to get the text entered by the user as well as any literal characters defined in the mask, use the ValueMaskFormat property as IncludeLiterals. It does not include prompt characters in the Value property.

<syncfusion:SfMaskedEdit ValueMaskFormat="IncludeLiterals"
                         Mask="\([0-9]\d{2}\) [0-9]\d{2}-[0-9]\d{3}" 
                         MaskType = "RegEx"
                         Name="sfMaskedEdit"/>
SfMaskedEdit sfMaskedEdit = new SfMaskedEdit();
sfMaskedEdit.ValueMaskFormat = MaskFormat.IncludeLiterals;
sfMaskedEdit.MaskType = MaskType.RegEx;
sfMaskedEdit.Mask = @"\([0-9]\d{2}\) [0-9]\d{2}-[0-9]\d{3}";

WPF MaskedTextBox displays Value with Literals

View Sample in GitHub

Value with prompt character

If you want to get the text entered by the user as well as any prompt characters defined in the mask, use the ValueMaskFormat property as IncludePrompt. It does not include literal characters in the Value property.

<syncfusion:SfMaskedEdit ValueMaskFormat="IncludePrompt"
                         Mask="\([0-9]\d{2}\) [0-9]\d{2}-[0-9]\d{3}" 
                         MaskType = "RegEx"
                         Name="sfMaskedEdit"/>
SfMaskedEdit sfMaskedEdit = new SfMaskedEdit();
sfMaskedEdit.ValueMaskFormat = MaskFormat.IncludePrompt;
sfMaskedEdit.MaskType = MaskType.RegEx;
sfMaskedEdit.Mask = @"\([0-9]\d{2}\) [0-9]\d{2}-[0-9]\d{3}";

WPF MaskedTextBox displays Value with Prompt Character

View Sample in GitHub

Value with prompt characters and literals

If you want to get the text entered by the user as well as any literals and the prompt character defined in the mask, use the ValueMaskFormat property as IncludePromptAndLiterals. It includes the prompt and literal characters in the Value property.

<syncfusion:SfMaskedEdit ValueMaskFormat="IncludePromptAndLiterals"
                         Mask="\([0-9]\d{2}\) [0-9]\d{2}-[0-9]\d{3}" 
                         MaskType = "RegEx"
                         Name="sfMaskedEdit"/>
SfMaskedEdit sfMaskedEdit = new SfMaskedEdit();
sfMaskedEdit.ValueMaskFormat = MaskFormat.IncludePromptAndLiterals;
sfMaskedEdit.MaskType = MaskType.RegEx;
sfMaskedEdit.Mask = @"\([0-9]\d{2}\) [0-9]\d{2}-[0-9]\d{3}";

WPF MaskedTextBox displays Value with Prompt and Literals Character

View Sample in GitHub

Input validation

You can validate the user input on key press or control lost focus.

Input validation on each input entering

You can validate the user input on each key press. You can enable it by setting the ValidationMode property as KeyPress. The default value of the ValidationMode property is KeyPress.

<syncfusion:SfMaskedEdit ValidationMode="KeyPress" 
                         Mask="\+1 [0-9]\d{2}-[0-9]\d{2}-[0-9]\d{3}" 
                         MaskType = "RegEx"
                         Name="sfMaskedEdit"/>
SfMaskedEdit sfMaskedEdit = new SfMaskedEdit();
sfMaskedEdit.ValidationMode = InputValidationMode.KeyPress;
sfMaskedEdit.MaskType = MaskType.RegEx;
sfMaskedEdit.Mask = @"\+1 [0-9]\d{2}-[0-9]\d{2}-[0-9]\d{3}";

Validating Input on Key Press in WPF MaskedTextBox

View Sample in GitHub

Input validation on lost focus

You can validate the user input when the control loses focus. You can enable it by setting the ValidationMode property as LostFocus.

<syncfusion:SfMaskedEdit ValidationMode="LostFocus" 
                         Mask="\+1 [0-9]\d{2}-[0-9]\d{2}-[0-9]\d{3}" 
                         MaskType = "RegEx"
                         Name="sfMaskedEdit"/>
SfMaskedEdit sfMaskedEdit = new SfMaskedEdit();
sfMaskedEdit.ValidationMode = InputValidationMode.LostFocus;
sfMaskedEdit.MaskType = MaskType.RegEx;
sfMaskedEdit.Mask = @"\+1 [0-9]\d{2}-[0-9]\d{2}-[0-9]\d{3}";

Validating Input without Focus in WPF MaskedTextBox

View Sample in GitHub

Get the validation result

You can check whether the input validation has succeeded or failed by using the HasError property once validation is completed. The HasError property returns the following results,

  • True - If validation is successful.
  • False - If validation is failed.
<syncfusion:SfMaskedEdit ValidationMode="LostFocus" 
                         Mask="\+1 [0-9]\d{2}-[0-9]\d{2}-[0-9]\d{3}" 
                         MaskType = "RegEx"
                         LostFocus="SfMaskedEdit_LostFocus" 
                         Name="sfMaskedEdit"/>
SfMaskedEdit sfMaskedEdit = new SfMaskedEdit();
sfMaskedEdit.ValidationMode = InputValidationMode.LostFocus;
sfMaskedEdit.MaskType = MaskType.RegEx;
sfMaskedEdit.Mask = @"\+1 [0-9]\d{2}-[0-9]\d{2}-[0-9]\d{3}";
sfMaskedEdit.LostFocus += SfMaskedEdit_LostFocus;

You can get the validation result as follows,

private void SfMaskedEdit_LostFocus(object sender, RoutedEventArgs e) {
    if ((sender as SfMaskedEdit).HasError){
        MessageBox.Show("Please enter the correct phone number");
    }
}

WPF MaskedTextBox displays Validation Result

Indicates error on invalid input

After input validation fails, you can indicate the invalid input to the user by showing an error border. The error border automatically disappears when the input validation succeeds. You can change the error border color by using the ErrorBorderBrush property. The default value of the ErrorBorderBrush property is Red.

<syncfusion:SfMaskedEdit ErrorBorderBrush="Yellow" 
                         Name="sfMaskedEdit"/>
SfMaskedEdit sfMaskedEdit = new SfMaskedEdit();
sfMaskedEdit.ErrorBorderBrush = Brushes.Yellow;

WPF MaskedTextBox displays Error Validation

View Sample in GitHub

Indicates the missed input

You can indicate to the user to enter the missed input by using the prompt character. You can change the prompt character by using the PromptChar property. The default prompt character is _.

<syncfusion:SfMaskedEdit PromptChar="X"
                         MaskType="RegEx"
                         Mask="\+1 [0-9]\d{2}-[0-9]\d{2}-[0-9]\d{3}"
                         Name="sfMaskedEdit"/>
SfMaskedEdit sfMaskedEdit = new SfMaskedEdit();
sfMaskedEdit.PromptChar = 'X';
sfMaskedEdit.MaskType = MaskType.RegEx;
sfMaskedEdit.Mask = @"\+1 [0-9]\d{2}-[0-9]\d{2}-[0-9]\d{3}";

WPF MaskedTextBox displays Prompt Character

View Sample in GitHub

Display the prompt character on got focus

By default, the prompt character is shown only while entering the input. If you want to show the prompt character when the control gets focus, use the ShowPromptOnFocus property with the value true. The default value of the ShowPromptOnFocus property is false.

<syncfusion:SfMaskedEdit ShowPromptOnFocus="True"
                         PromptChar="X"
                         MaskType="RegEx"
                         Mask="\+1 [0-9]\d{2}-[0-9]\d{2}-[0-9]\d{3}"
                         Name="sfMaskedEdit"/>
SfMaskedEdit sfMaskedEdit = new SfMaskedEdit();
sfMaskedEdit.ShowPromptOnFocus = true;
sfMaskedEdit.PromptChar = 'X';
sfMaskedEdit.MaskType = MaskType.RegEx;
sfMaskedEdit.Mask = @"\+1 [0-9]\d{2}-[0-9]\d{2}-[0-9]\d{3}";

WPF MaskedTextBox displays Prompt Character

View Sample in GitHub

Setting the watermark

You can prompt the user with instructions or important information when the control is not in focus and no valid character has been entered. You can set the watermark by using the Watermark property. The default value of the Watermark property is null.

<syncfusion:SfMaskedEdit Watermark="Type here" 
                         Name="sfMaskedEdit"/>
SfMaskedEdit sfMaskedEdit = new SfMaskedEdit();
sfMaskedEdit.Watermark = "Type here";

WPF MaskedTextBox with Watermark Text

View Sample in GitHub

Custom template for Watermark

You can change the template of the Watermark by using the WatermarkTemplate property.

<syncfusion:SfMaskedEdit Watermark="Type here" 
                         Name="sfMaskedEdit">
    <syncfusion:SfMaskedEdit.WatermarkTemplate >
        <DataTemplate>
            <Border Background="Yellow">
                <TextBlock Foreground="Blue" 
                           FontWeight="Bold"
                           Text="{Binding}" 
                           TextAlignment="Center"/>
            </Border>
        </DataTemplate>
    </syncfusion:SfMaskedEdit.WatermarkTemplate>
</syncfusion:SfMaskedEdit>

Customizing Watermark Text in WPF MaskedTextBox

View Sample in GitHub

Value changed notification

You can receive a notification when the value of the SfMaskedEdit.Value property changes by using the ValueChanged event.

Your valid input character is updated to the Value property based on the ValidationMode property.
Refer Input Validation to know more about the ValidationMode.

<syncfusion:SfMaskedEdit ValueChanged="SfMaskedEdit_ValueChanged" 
                         Name="sfMaskedEdit"/>
SfMaskedEdit sfMaskedEdit = new SfMaskedEdit();	
sfMaskedEdit.ValueChanged += SfMaskedEdit_ValueChanged;

You can handle the event as follows,

private void SfMaskedEdit_ValueChanged(object sender, EventArgs e) {
   MessageBox.Show("Value changed");
}