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 个解决方案
#1
10
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:
如果你只想要字母 - 所以从a到z,小写或大写,排除其他所有(数字,空格,符号),你可以像这样修改你的函数:
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;
}
}
#2
3
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;
}
#3
2
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.
谢谢。
#4
0
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.
在文本框中使用onkeyup并检查按下的键的键码,如果它在65和90之间,则允许清空文本框。
#1
10
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:
如果你只想要字母 - 所以从a到z,小写或大写,排除其他所有(数字,空格,符号),你可以像这样修改你的函数:
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;
}
}
#2
3
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;
}
#3
2
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.
谢谢。
#4
0
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.
在文本框中使用onkeyup并检查按下的键的键码,如果它在65和90之间,则允许清空文本框。