简体   繁体   English

验证字母的Javascript

[英]Javascript to validate letters

I cannot seem to figure out how to get this script to validate that only letters are being entered. 我似乎无法弄清楚如何获取此脚本以验证仅输入字母。 So if a number is entered, then an error should be returned. 因此,如果输入数字,则应该返回错误。

HTML 的HTML

<form name="myForm" action="demo_form.asp"
onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">

Javascipt 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>

This might be best done with HTML5's new pattern attribute. 最好使用HTML5的新pattern属性来完成此操作。 However, it doesn't work in Safari or in Internet Explorer 9-. 但是,它在Safari或Internet Explorer 9-中不起作用。

From the Mozilla Developer Network 来自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. 使用title属性描述模式以帮助用户。 This attribute applies when the value of the type attribute is text, search, tel, url, email or password; 当type属性的值为text,search,tel,url,email或password时,此属性适用。 otherwise it is ignored. 否则将被忽略。 The regular expression language is the same as JavaScript's. 正则表达式语言与JavaScript相同。 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> 

For browsers from the stone age, just use regex. 对于石器时代的浏览器,只需使用正则表达式即可。

if (!/^[a-z]+$/i).test(exp)) {
    return false;
}

Explanation 说明

The ^ and $ characters signal that the string should both start and end with a letter ^$字符表示字符串应以字母开头和结尾

The + modifier indicates that we're searching for one or more such letters. +修饰符表示我们正在搜索一个或多个这样的字母。

Finally, the case-insensitive flag i is raised to indicate it can be upper or lower case. 最后,不区分大小写的标志i升高以指示它可以是大写或小写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM