我们经常需要用户在表单中输入数字,用户不小心使用了全角状态输入数字,但是在程序中全角的数字是不能直接转换为数字的。这种全角数字的错误处理起来就有些麻烦了。对一些没有经验用户来说明明已经输入数字了,怎么还是提示输入不是数字呢?这样就很影响用户体验。
解决的方法有两个:
解决方法1:
在input的style设置ime-mode为disabled,禁用中文输入法。
1 <asp:TextBox ID="tbLink" runat="server" MaxLength="32" style="ime-mode:disabled;"></asp:TextBox>
优点:简单实用,
缺点:只能在ie浏览器中使用。
解决方法2:
使用函数将全角数字转换为半角数字
1 /// <summary>
2 /// 转换为半角字符串
3 /// </summary>
4 /// <param name="text"></param>
5 /// <returns></returns>
6 public static string ConvertToHalf(string text)
7 {
8 char[] c = text.ToCharArray();
9
10 for (int i = 0; i < c.Length; i++)
11 {
12 byte[] b = System.Text.Encoding.Unicode.GetBytes(c, i, 1);
13 if (b.Length == 2)
14 {
15 if (b[1] == 255)
16 {
17 b[0] = (byte)(b[0] + 32);
18 b[1] = 0;
19 c[i] = System.Text.Encoding.Unicode.GetChars(b)[0];
20 }
21 }
22 }
23 return new string(c);
24 }
2 /// 转换为半角字符串
3 /// </summary>
4 /// <param name="text"></param>
5 /// <returns></returns>
6 public static string ConvertToHalf(string text)
7 {
8 char[] c = text.ToCharArray();
9
10 for (int i = 0; i < c.Length; i++)
11 {
12 byte[] b = System.Text.Encoding.Unicode.GetBytes(c, i, 1);
13 if (b.Length == 2)
14 {
15 if (b[1] == 255)
16 {
17 b[0] = (byte)(b[0] + 32);
18 b[1] = 0;
19 c[i] = System.Text.Encoding.Unicode.GetChars(b)[0];
20 }
21 }
22 }
23 return new string(c);
24 }