javascript validation to allow only numbers and alphabets

前端 未结 3 1220
执念已碎
执念已碎 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 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);
     }

    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;
    
     }

提交回复
热议问题