[英]javascript regex (username validation)
I want to enforce that我想强制执行
How do I restrict the two rules in javascript?如何在javascript中限制这两个规则?
Below is my code (jsp) for username regex.下面是我的用户名正则表达式代码(jsp)。 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 AZ, az and '-' are acceptable."); document.frm.firstName.focus(); return false; } }<\/code><\/pre>
Thanks!谢谢!
"
The code you have looks fine, aside from the inconsistent variable reference (see the comment by Josh Purvis ).除了不一致的变量引用(请参阅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
我鼓励你完成这个正则表达式教程
Here's the validation function I came up with, tailor it for your own use-cases:这是我想出的验证功能,根据您自己的用例进行定制:
function isUserNameValid(username) {
/*
Usernames can only have:
- Lowercase Letters (a-z)
- Numbers (0-9)
- Dots (.)
- Underscores (_)
*/
const res = /^[a-z0-9_\.]+$/.exec(username);
const valid = !!res;
return valid;
}
Usernames can only use letters, numbers, underscores, and periods.用户名只能使用字母、数字、下划线和句点。
const onValidUsername = (val) => {
const usernameRegex = /^[a-z0-9_.]+$/
return usernameRegex.test(val)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.