使用正则表达式改变文本框事件

使用正则表达式改变文本框事件

开发工具与关键技术:Visual Studio 2015、WPF
作者:黄元进
撰写时间: 2019年5月14日

首先构建一个窗口,在Grid布局中写入TextBlock(文本块)以及TextBox(文本框),文本框中设置取一个名字,现国内电话号码只有十一位数,所以用MaxLength来设置,用TextChanged新建一个事件,页面较简陋。用XAML代码实现:

<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>

接着就跳转到后台代码,运用正则表达式判断是否匹配,代码如下:

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 = "";
               }
            }
      }
   }
}

效果图1(输入的手机号码格式不对做出的判断语句,设置了只能输入11位数)
在这里插入图片描述

效果图2(输入的手机号码格式正确就成立,设置了只能输入11位数
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44547949/article/details/90211651
今日推荐