Use regular expressions to change the text box events

Use regular expressions to change the text box events

Development tools and key technologies: Visual Studio 2015, WPF
Author: Huang Yuan into
writing time: May 14, 2019

First, construct a window, the TextBlock write Grid layout (text block), and set the TextBox (text box) a name text box, domestic phone number is now only eleven digits, so use MaxLength setting, with new TextChanged an event page more primitive. With XAML code to achieve:

<Window x:Class="Wpf1.Window2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Wpf1"
Title="使用正则表达式改变文本框事件" Height="300"Width="300">
<Grid>
<TextBlock Text="手机号码:"/>
<TextBox x:Name="cs"Margin="67,0,46.6,241" MaxLength="11" TextChanged="cs_TextChanged"/>
</Grid>
</Window>

Then the code jumps to the background, the use of the regular expression match is determined, as follows:

usingSystem.Text.RegularExpressions;
usingSystem.Windows;
usingSystem.Windows.Controls;

namespace Wpf1
{
/// <summary>
/// Window2.xaml 的交互逻辑
/// </summary>
public partial class Window2 : Window
{
public Window2()
{
InitializeComponent();
}
private void cs_TextChanged(objectsender, TextChangedEventArgs e)
{
string strcs = cs.Text.Trim();
if (strcs.Length == 11)
{
//使用正则表达式判断是否匹配 
if (!Regex.IsMatch(strcs, @"^0?(13[0-9]|14[5-9]|15[012356789]|166|17[0-8]|18[0-9]|19[89])[0-9]{8}$"))
{
MessageBox.Show("手机号格式不对,请重新输入!");
cs.Text = "";
               }
            }
      }
   }
}

Renderings 1 (enter phone number format does not make a judgment statement, provided only enter 11 digits)
Here Insert Picture Description

Effect 2 (Enter the phone number on the establishment of the correct format, set up only enter 11 digits
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/weixin_44547949/article/details/90211651