Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
134
rated 0 times [  135] [ 1]  / answers: 1 / hits: 16328  / 8 Years ago, tue, june 7, 2016, 12:00:00

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>

More From » asp.net

 Answers
24

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) />





EDIT:
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) />




[#61868] Monday, June 6, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
deniseryannd

Total Points: 169
Total Questions: 85
Total Answers: 96

Location: Virgin Islands (U.S.)
Member since Fri, May 7, 2021
3 Years ago
;