Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 341
thevan Avatar asked Jul 16 '14 07:07

thevan


2 Answers

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>
like image 195
Rahul Tripathi Avatar answered Sep 29 '22 13:09

Rahul Tripathi


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/

like image 42
Deepu Sasidharan Avatar answered Sep 29 '22 11:09

Deepu Sasidharan