如何使输入字段仅接受javaScript中的字母? [英] How do I make an input field accept only letters in javaScript?
本文介绍了如何使输入字段仅接受javaScript中的字母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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?
推荐答案
如果你只想要字母 - 那么从 a 到 z ,小写或大写,不包括其他所有内容(数字,空格,符号),您可以像这样修改您的函数:
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;
}
}
这篇关于如何使输入字段仅接受javaScript中的字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文