我似乎无法弄清楚如何让这个脚本验证是否只输入了字母。因此,如果输入数字,则应返回错误。
HTML
<form name="myForm" action="demo_form.asp"
onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
Javascipt
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "") {
alert("First name must be filled out");
return false;
}
}
</script>
最佳答案
这可能最好使用 HTML5 的新 pattern
属性来完成。但是,它在 Safari 或 Internet Explorer 9- 中不起作用。
来自 Mozilla 开发者网络
A regular expression that the control's value is checked against. The pattern must match the entire value, not just some subset. Use the title attribute to describe the pattern to help the user. This attribute applies when the value of the type attribute is text, search, tel, url, email or password; otherwise it is ignored. The regular expression language is the same as JavaScript's. The pattern is not surrounded by forward slashes.
<form action="demo_form.asp">
Username: <input type="text" name="username"
pattern="[A-Za-z]+" title="Your username">
<input type="submit">
</form>
对于石器时代的浏览器,只需使用正则表达式即可。
if (!/^[a-z]+$/i).test(exp)) {
return false;
}
解释
^
和 $
字符表示字符串应该以字母开头和结尾
+
修饰符表示我们正在搜索一个或多个这样的字母。
最后,不区分大小写的标志 i
被提升以指示它可以是大写或小写。
关于用于验证字母的 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35951079/