用于验证字母的 Javascript

标签 javascript html regex string validation

我似乎无法弄清楚如何让这个脚本验证是否只输入了字母。因此,如果输入数字,则应返回错误。

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/

相关文章:

javascript - SVG:根据值定位RECT

javascript - 更改事件不适用于动态生成的元素 - Jquery

PHP 相当于这个 Javascript

javascript - 如何在 Ext JS Grid 上创建带有标签的文本字段?

javascript - 如何检查相邻字符是什么?

javascript - jQuery 插件仅适用于最后一个选择器

html - 为什么样式表只适用于索引页,而不适用于索引页的任何扩展? (使用 Jinja 的模板)

Javascript 库未加载以用于加载页面的部分 View

regex - 正则表达式正向前瞻子串

python - ansible正则表达式替换所有匹配的string1,排除string2