Skip to content Skip to sidebar Skip to footer

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 b

Solution 1:

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:

functionallowAlphaNumericSpace(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();
  }
}
<inputtype="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.

functionallowAlphaNumericSpace(thisInput) {
  thisInput.value = thisInput.value.split(/[^a-zA-Z0-9 ]/).join('');
}
<inputtype="text"onkeyup="allowAlphaNumericSpace(this)" />

Solution 2:

You can use regex to test your input , with something like this :

var regexp = newRegExp(/^[a-zA-Z0-9 ]+$/);
var str="sqdqsd qsd125";
var str2="sqdqsdqsd12;5";
console.log(regexp.test(str));
console.log(regexp.test(str2));

https://jsfiddle.net/Tintin37/7Lj7r9zp/1/

EDIT

I added a little snippet ;)

functiononlyAlphabets(e, t) {
   var regexp = newRegExp(/^[a-zA-Z0-9 ]*$/);
   console.log(regexp.test(t.value));
   return regexp.test(t.value);
 }
<inputtype="text"onkeyup="return onlyAlphabets(event,this);" />

EDIT2

With the desired behavior ;)

functiononlyAlphabets(e, t) {
   var regexp = newRegExp(/^[a-zA-Z0-9 ]*$/);
   if (window.event) {
     keynum = e.keyCode;
   } elseif (e.which) {
     keynum = e.which;
   }
   var test = regexp.test(String.fromCharCode(keynum));
   return test;

 }
<inputtype="text"onkeypress="return onlyAlphabets(event,this);" />

Solution 3:

The reason your code wont accept numbers is because numbers have their own character code as well. The character code for 1, for example, is 48. To include numbers, you should include this in your if statement:

(charCode >= 48 && charcode <= 57)

Not sure why spaces aren't working, but see if the above helps!

Post a Comment for "Javascript Validation To Allow Only Numbers And Alphabets"