How to validate html textbox not to allow special characters and space?

我们两清 提交于 2019-12-17 18:59:10

问题


This is my html:

 <input type="text" name="folderName">

Here, I want to validate the textbox value by not allowing to key in special characters and space. But it should allow underscore.

How to validate this textbox?


回答1:


You may try to use this function:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script type="text/javascript">
    function blockSpecialChar(e){
        var k;
        document.all ? k = e.keyCode : k = e.which;
        return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
        }
    </script>
</head>
<body>
    <form id="frm" runat="server">
      <input type="text" name="folderName"  onkeypress="return blockSpecialChar(event)"/>
    </form>
</body>
</html>



回答2:


Try like this

$(document).ready(function () {
    $("#sub").click(function(){
var fn = $("#folderName").val();
    var regex = /^[0-9a-zA-Z\_]+$/
    alert(regex.test(fn));
});
});

This return false for special chars and spaces and return true for underscore, digits and alphabets.

Fiddle: http://jsfiddle.net/7C5nP/




回答3:


You may try to use this function:

<input class="form-control" onkeypress="return ((event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123) || event.charCode == 8 || event.charCode == 32 || (event.charCode >= 48 && event.charCode <= 57));" id="name" formControlName="name" type="text" autocomplete="off" value="">

It works for me.




回答4:


You can use jQuery + jQuery Validation Plugin. That will make it that easy:

This will allow the user only to type letters plus underscore

 <input type="text" data-validation="alphanumeric" data-validation-allowing="_">

Link to the jQuery Plugin: http://formvalidator.net/index.html




回答5:


You have to create a javascript function that will do the validation. You could find severals exemple around the web. You could take a look on that website: javascript-validation and pay attention to the Email Validation in Javascript part (you will have to adapt a little).



来源:https://stackoverflow.com/questions/24774367/how-to-validate-html-textbox-not-to-allow-special-characters-and-space

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!