Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript validation to allow only numbers and alphabets

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>

1 Answers

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)" />
like image 165
Seth M. Avatar answered Oct 24 '25 17:10

Seth M.