javascript正则表达式(用户名验证) [英] javascript regex (username validation)
问题描述
我想强制执行
- 输入的firstname应该只包含字符AZ,az和 -
- 输入登录名应该只包含字母数字字符
如何在javascript中限制这两个规则?
How do I restrict the two rules in javascript?
以下是我的用户名正则表达式的代码(jsp)。但它没有正常工作。
Below is my code (jsp) for username regex. But it's not working properly.
function validateForm(){
var nameRegex = /^[a-zA-Z\-]+$/;
var validfirstUsername = document.frm.firstName.value.match(nameRegex);
if(validUsername == null){
alert("Your first name is not valid. Only characters A-Z, a-z and '-' are acceptable.");
document.frm.firstName.focus();
return false;
}
}
谢谢!
推荐答案
除了不一致的变量引用之外,你所拥有的代码看起来还不错(参见 Josh Purvis的评论)。
The code you have looks fine, aside from the inconsistent variable reference (see the comment by Josh Purvis).
以下正则表达式适用于您的名字规范:
The following regex is fine for your first name spec:
var nameRegex = /^[a-zA-Z\-]+$/;
为您的用户名检查添加数字非常简单:
Adding digits for your username check is straightforward:
var usernameRegex = /^[a-zA-Z0-9]+$/;
注意:编写正则表达式的方法有很多种。我选择提供与您开始时匹配的版本。我鼓励您完成正则表达式教程
Note: There are many ways to write regular expressions. I've chosen to provide a version that matches what you started with. I encourage you to work through this Regular Expression Tutorial
这篇关于javascript正则表达式(用户名验证)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!