WPF文本框中必需的字段验证 [英] Required field validation in WPF text box
本文介绍了WPF文本框中必需的字段验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一种简单的方法来验证文本框(必填字段)。当用户按下按钮时,它应该检查所有必填字段的存在。
我尝试过:
< Window.Resources >
< ControlTemplate < span class =code-attribute> x:Key = validationTemplate >
< DockPanel >
< < span class =code-leadattribute> TextBlock Foreground = 红色 FontSize = 25 文字 < span class =code-keyword> = * DockPanel.Dock = 右 > < / TextBlock >
< AdornedElementPlaceholder / >
< / DockPanel >
< / ControlTemplate >
< / Window.Resources >
< 网格 >
< 按钮 内容 = 按钮 HorizontalAlignment = Left 高度 = < span class =code-keyword> 26 保证金 = 62,213,0,0 < span class =code-attribute> VerticalAlignment = Top 宽度 = 121 点击 = Button_Click_1 / >
< TextBox x:名称 = txtEmail1 文字 = 高度 = 61 保证金 = 116, 10,194,0 Validation.ErrorTemplate = {StaticResource validationTemplate} / > ;
< / Grid >
解决方案
您可能需要检查文本字符串是否为空,如果它不是通过正则表达式验证
<前lang =c#> 如果(txtEmail1.Text.Equals( string .empty))
{
MessageBox.Show( 需要文字);
}
其他
{
// < span class =code-comment>使用正则表达式检查电子邮件验证
正则表达式regex = 新正则表达式( @ ^([\\\\\ - ] +)@([\\\\ - ] +)((\。 (\w){2,3})+)
跨度>);
匹配匹配= regex.Match(电子邮件);
if (match.Success)
{
// < span class =code-comment>电子邮件是正确的,在这里写下你要做的代码
}
else
{
MessageBox.Show( 电子邮件不正确);
}
}
I need a simple way to validate of text boxes (Required Field). It should check all mandatory field existence , when user press button.
What I have tried:
<Window.Resources>
<ControlTemplate x:Key="validationTemplate">
<DockPanel>
<TextBlock Foreground="Red" FontSize="25" Text="*" DockPanel.Dock="Right"></TextBlock>
<AdornedElementPlaceholder/>
</DockPanel>
</ControlTemplate>
</Window.Resources>
<Grid>
<Button Content="Button" HorizontalAlignment="Left" Height="26" Margin="62,213,0,0" VerticalAlignment="Top" Width="121" Click="Button_Click_1"/>
<TextBox x:Name="txtEmail1" Text="" Height="61" Margin="116,10,194,0" Validation.ErrorTemplate="{StaticResource validationTemplate}"/>
</Grid>
解决方案
You maybe need to check if text string is empty , and if it isnt validate via regex
if(txtEmail1.Text.Equals(string.empty)) { MessageBox.Show("Text is required"); } else { // check email validation with regex Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)
"); Match match = regex.Match(email); if (match.Success) { // email is correct , write here your to do code } else { MessageBox.Show("Email is not correct "); } }
这篇关于WPF文本框中必需的字段验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文