javascript validation to allow only numbers and alphabets

前端 未结 3 1197
执念已碎
执念已碎 2021-01-21 05:29

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 fin

相关标签:
3条回答
  • 2021-01-21 05:59

    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!

    0 讨论(0)
  • 2021-01-21 06:02

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

    0 讨论(0)
  • 2021-01-21 06:08

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

    var regexp = new RegExp(/^[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 ;)

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

    EDIT2

    With the desired behavior ;)

     function onlyAlphabets(e, t) {
       var regexp = new RegExp(/^[a-zA-Z0-9 ]*$/);
       if (window.event) {
         keynum = e.keyCode;
       } else if (e.which) {
         keynum = e.which;
       }
       var test = regexp.test(String.fromCharCode(keynum));
       return test;
    
     }
    <input type="text" onkeypress="return onlyAlphabets(event,this);" />

    0 讨论(0)
提交回复
热议问题