How do I make an input field accept only letters i

2019-01-14 13:52发布

function validate() {
if(document.myForm.name.value =="" ){
alert("Enter a name");
document.myForm.name.focus();
return false;
}

This is what I've written it for an empty string, now i need it to accept only letters?

4条回答
祖国的老花朵
2楼-- · 2019-01-14 14:06

If you want only letters - so from a to z, lower case or upper case, excluding everything else (numbers, blank spaces, symbols), you can modify your function like this:

function validate() {
    if (document.myForm.name.value == "") {
        alert("Enter a name");
        document.myForm.name.focus();
        return false;
    }
    if (!/^[a-zA-Z]*$/g.test(document.myForm.name.value)) {
        alert("Invalid characters");
        document.myForm.name.focus();
        return false;
    }
}
查看更多
祖国的老花朵
3楼-- · 2019-01-14 14:12

Try this:

var alphaExp = /^[a-zA-Z]+$/;
            if(document.myForm.name.match(alphaExp))
            {
                //Your logice will be here.
            }
            else{
                alert("Please enter only alphabets");
            }

Thanks.

查看更多
Lonely孤独者°
4楼-- · 2019-01-14 14:16

Use onkeyup on the text box and check the keycode of the key pressed, if its between 65 and 90, allow else empty the text box.

查看更多
Luminary・发光体
5楼-- · 2019-01-14 14:25
function alphaOnly(event) {
  var key = event.keyCode;
  return ((key >= 65 && key <= 90) || key == 8);
};

or

function lettersOnly(evt) {
       evt = (evt) ? evt : event;
       var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
          ((evt.which) ? evt.which : 0));
       if (charCode > 31 && (charCode < 65 || charCode > 90) &&
          (charCode < 97 || charCode > 122)) {
          alert("Enter letters only.");
          return false;
       }
       return true;
     }
查看更多
登录 后发表回答