1 核心代码(校验当前字符是否为数字或退格键)
public class Utility
{
/// <summary>
/// 判断按键是否为数字或退格键
/// </summary>
/// <param name="ch">按键字符</param>
/// <returns>是:true</returns>
public static bool IsInputNumber(char ch)
{
return ch > 47 && ch < 58 || ch == 8;
}
}
1 校验身份号
private void txt_Card_KeyPress(object sender, KeyPressEventArgs e)
{
var txt = sender as TextBox;
if (txt?.TextLength <= 18) //文本框文本长度限制
{
if (Utility.IsInputNumber(e.KeyChar))
{
e.Handled = false;//需为数字,包含对退格键(Backspace)的判断
}
else if (txt.TextLength + 1 == 18 && (e.KeyChar == 88 || e.KeyChar == 120))
{
e.KeyChar = 'X';
e.Handled = false;//末尾为X或x,若为x则修改为X
}
}
e.Handled = true;
}
2 校验手机号码
private void txt_Number_KeyPress(object sender, KeyPressEventArgs e)
{
var txt = sender as TextBox;
if (txt?.TextLength <= 11) //文本框文本长度限制
{
if (Utility.IsInputNumber(e.KeyChar))
{
e.Handled = false;//需为数字,包含对退格键(Backspace)的判断
}
}
e.Handled = true;
}
3 文本框仅允许输入浮点型数据
按键事件配合文本框改变事件完成
//按键验证:double类型
private void txt_Number_KeyPress(object sender, KeyPressEventArgs e)
{
var txt = sender as TextBox;
if (txt != null)
{
bool isHandled = true;
if (Utility.IsInputNumber(e.KeyChar))
{
isHandled = false;//需为数字,包含对退格键(Backspace)的判断
}
else if (txt.TextLength > 0 && !txt.Text.Contains(".") && e.KeyChar == '.')
{
isHandled = false;//从第二位开始仅允许输入一个句点(.),
}
e.Handled = isHandled;
}
}
//监控到第一位为小数点时,向数据头添加0
private void txt_Number_TextChanged(object sender, EventArgs e)
{
var txt = sender as TextBox;
if (txt != null)
{
string value = txt.Text;
if (!string.IsNullOrWhiteSpace(value))
{
if (value[0] == '.')
{
value = $"0{value}";
}
}
txt.Text = value;
}
}