Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6706815
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T07:33:53+00:00 2026-05-26T07:33:53+00:00

in my WPF textbox i have validated it on following events TextChanged PreviewTextInput so

  • 0

in my WPF textbox i have validated it on following events

TextChanged
PreviewTextInput

so that user cannot allow special characters in it , but user is able to paste the special character either through ctrl+v key or by right click of mouse and paste.

How to validate these two extra events on textbox.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T07:33:54+00:00Added an answer on May 26, 2026 at 7:33 am

    XAML:

     <TextBox b:Masking.Mask="someregularExpressionhere"/>  
    

    Code behind :

       /// <summary>
        /// Provides masking behavior for any <see cref="TextBox"/>.
        /// </summary>
        public static class Masking
        {
                private static readonly DependencyPropertyKey _maskExpressionPropertyKey = DependencyProperty.RegisterAttachedReadOnly("MaskExpression",
                        typeof(Regex),
                        typeof(Masking),
                        new FrameworkPropertyMetadata());
    
                /// <summary>
                /// Identifies the <see cref="Mask"/> dependency property.
                /// </summary>
                public static readonly DependencyProperty MaskProperty = DependencyProperty.RegisterAttached("Mask",
                        typeof(string),
                        typeof(Masking),
                        new FrameworkPropertyMetadata(OnMaskChanged));
    
                /// <summary>
                /// Identifies the <see cref="MaskExpression"/> dependency property.
                /// </summary>
                public static readonly DependencyProperty MaskExpressionProperty = _maskExpressionPropertyKey.DependencyProperty;
    
                /// <summary>
                /// Gets the mask for a given <see cref="TextBox"/>.
                /// </summary>
                /// <param name="textBox">
                /// The <see cref="TextBox"/> whose mask is to be retrieved.
                /// </param>
                /// <returns>
                /// The mask, or <see langword="null"/> if no mask has been set.
                /// </returns>
                public static string GetMask(TextBox textBox)
                {
                        if (textBox == null)
                        {
                                throw new ArgumentNullException("textBox");
                        }
    
                        return textBox.GetValue(MaskProperty) as string;
                }
    
                /// <summary>
                /// Sets the mask for a given <see cref="TextBox"/>.
                /// </summary>
                /// <param name="textBox">
                /// The <see cref="TextBox"/> whose mask is to be set.
                /// </param>
                /// <param name="mask">
                /// The mask to set, or <see langword="null"/> to remove any existing mask from <paramref name="textBox"/>.
                /// </param>
                public static void SetMask(TextBox textBox, string mask)
                {
                        if (textBox == null)
                        {
                                throw new ArgumentNullException("textBox");
                        }
    
                        textBox.SetValue(MaskProperty, mask);
                }
    
                /// <summary>
                /// Gets the mask expression for the <see cref="TextBox"/>.
                /// </summary>
                /// <remarks>
                /// This method can be used to retrieve the actual <see cref="Regex"/> instance created as a result of setting the mask on a <see cref="TextBox"/>.
                /// </remarks>
                /// <param name="textBox">
                /// The <see cref="TextBox"/> whose mask expression is to be retrieved.
                /// </param>
                /// <returns>
                /// The mask expression as an instance of <see cref="Regex"/>, or <see langword="null"/> if no mask has been applied to <paramref name="textBox"/>.
                /// </returns>
                public static Regex GetMaskExpression(TextBox textBox)
                {
                        if (textBox == null)
                        {
                                throw new ArgumentNullException("textBox");
                        } 
    
                        return textBox.GetValue(MaskExpressionProperty) as Regex;
                }
    
                private static void SetMaskExpression(TextBox textBox, Regex regex)
                {
                        textBox.SetValue(_maskExpressionPropertyKey, regex);
                }
    
                private static void OnMaskChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
                {
                        var textBox = dependencyObject as TextBox;
                        var mask = e.NewValue as string;
                        textBox.PreviewTextInput -= textBox_PreviewTextInput;
                        textBox.PreviewKeyDown -= textBox_PreviewKeyDown;
                        DataObject.RemovePastingHandler(textBox, Pasting);
    
                        if (mask == null)
                        {
                                textBox.ClearValue(MaskProperty);
                                textBox.ClearValue(MaskExpressionProperty);
                        }
                        else
                        {
                                textBox.SetValue(MaskProperty, mask);
                                SetMaskExpression(textBox, new Regex(mask, RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace));
                                textBox.PreviewTextInput += textBox_PreviewTextInput;
                                textBox.PreviewKeyDown += textBox_PreviewKeyDown;
                                DataObject.AddPastingHandler(textBox, Pasting);
                        }
                }
    
                private static void textBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
                {
                        var textBox = sender as TextBox;
                        var maskExpression = GetMaskExpression(textBox);
    
                        if (maskExpression == null)
                        {
                                return;
                        }
    
                        var proposedText = GetProposedText(textBox, e.Text);
    
                        if (!maskExpression.IsMatch(proposedText))
                        {
                                e.Handled = true;
                        }
                }
    
                private static void textBox_PreviewKeyDown(object sender, KeyEventArgs e)
                {
                        var textBox = sender as TextBox;
                        var maskExpression = GetMaskExpression(textBox);
    
                        if (maskExpression == null)
                        {
                                return;
                        }
    
                        //pressing space doesn't raise PreviewTextInput - no idea why, but we need to handle
                        //explicitly here
                        if (e.Key == Key.Space)
                        {
                                var proposedText = GetProposedText(textBox, " ");
    
                                if (!maskExpression.IsMatch(proposedText))
                                {
                                        e.Handled = true;
                                }
                        }
                }
    
                private static void Pasting(object sender, DataObjectPastingEventArgs e)
                {
                        var textBox = sender as TextBox;
                        var maskExpression = GetMaskExpression(textBox);
    
                        if (maskExpression == null)
                        {
                                return;
                        }
    
                        if (e.DataObject.GetDataPresent(typeof(string)))
                        {
                                var pastedText = e.DataObject.GetData(typeof(string)) as string;
                                var proposedText = GetProposedText(textBox, pastedText);
    
                                if (!maskExpression.IsMatch(proposedText))
                                {
                                        e.CancelCommand();
                                }
                        }
                        else
                        {
                                e.CancelCommand();
                        }
                }
    
                private static string GetProposedText(TextBox textBox, string newText)
                {
                        var text = textBox.Text;
    
                        if (textBox.SelectionStart != -1)
                        {
                                text = text.Remove(textBox.SelectionStart, textBox.SelectionLength);
                        }
    
                        text = text.Insert(textBox.CaretIndex, newText);
    
                        return text;
                }
        }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a WPF textBox that is declared as ReadOnly <TextBox IsReadOnly=True IsTabStop=False Width=200
I have a WPF textbox, and perform the following actions Enter text as 12345
I have a simple control that extends the WPF TextBox control. The basic idea
I need a WPF Textbox that displays a phone number as (555) 555-5555 but
I have 2 TextBox es in my wpf app, one for user name and
I have an WPF usercontrol that has a TextBox. I set the text Underline
I have a WPF textbox on a form to allow input of a URI.
Is it possible to have a readonly WPF textbox display the first 3 characters
I have a WPF screen that displays a number of TextBox inputs. I have
This other SO question asks about an autocomplete textbox in WPF. Several people have

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.