javascript验证,仅允许数字和字母 [英] javascript validation to allow only numbers and alphabets

查看:47
本文介绍了javascript验证,仅允许数字和字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的javascript代码,如果我们输入数字和某些特殊字符,则仅允许输入字母,而仅输入时不接受它们,这很好,但是此javascript代码应允许数字,空格以及字母,我该怎么办这可以帮我吗

Below is my javascript code which allows only alphabets while entering if we enter numbers and some special characters it does not accept them while entering only this works fine but this javascript code should allow numbers,space also along with alphabets how can i do this can you please help me out

<script language="Javascript" type="text/javascript">

         function onlyAlphabets(e, t) {
             try {
                 if (window.event) {
                     var charCode = window.event.keyCode;
                 }
                 else if (e) {
                     var charCode = e.which;
                 }
                 else { return true; }
                 if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || charCode == 32)
                     return true;
                 else
                     return false;
             }
             catch (err) {
                 alert(err.Description);
             }
         }

    </script> 
<asp:TextBox ID="txtname" runat="server" onkeypress="return onlyAlphabets(event,this);"></asp:TextBox>

推荐答案

我可能会按照此处描述的方式做一些事情,同时添加所需的空格:

I'd probably do something along the lines of what is described here, while adding in the desired space inclusion: Best way to alphanumeric check in Javascript

例如,查看以下代码片段:

For example, check out this snippet:

function allowAlphaNumericSpace(e) {
  var code = ('charCode' in e) ? e.charCode : e.keyCode;
  if (!(code == 32) && // space
    !(code > 47 && code < 58) && // numeric (0-9)
    !(code > 64 && code < 91) && // upper alpha (A-Z)
    !(code > 96 && code < 123)) { // lower alpha (a-z)
    e.preventDefault();
  }
}

<input type="text" onkeypress="allowAlphaNumericSpace(event)" />

根据您的评论,我的快速而又肮脏的解决方案如下,尽管我确定必须存在更好的选择...请注意从"onkeypress"到"onkeyup"的切换,以确保在新值之后更新该值.字符已插入.

Based on your comment, my quick and dirty solution is as follows, though I'm sure a better option must exist... Make note of the switch from "onkeypress" to "onkeyup" to ensure that the value is updated after the new character is inserted.

function allowAlphaNumericSpace(thisInput) {
  thisInput.value = thisInput.value.split(/[^a-zA-Z0-9 ]/).join('');
}

<input type="text" onkeyup="allowAlphaNumericSpace(this)" />

这篇关于javascript验证,仅允许数字和字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆