为用户名验证创建正则表达式

问题描述 投票:0回答:2

我需要一些帮助来创建regexp。我只是不太了解如何创建一个正则表达式。如何使用这样的规则创建用户名验证

  1. 只允许使用大写,小写,下划线(_)和点(。)
  2. 以下划线(_)开头

我已经尝试过一些来自mozilla开发者网站的正则表达式,但这似乎不对

var usernameRegex = new RegExp(/_+[A-Za-z]/);
var usernameRegexFound = usernameRegex.test(username.value);
if (!usernameRegexFound) {
  msg = "Invalid Username";
}

我希望有一些像这样的用户名

_username = true

_username1 = false

.username = false

username = false

还有任何网站让我了解如何创建正则表达式,因为我还有更多的事情要处理它

function validuser(username) {
  var msg = "valid";
  var usernameRegex = new RegExp(/_+[A-Za-z]/);
  var usernameRegexFound = usernameRegex.test(username);
  if (!usernameRegexFound) {
    msg = "Invalid Username";
  }
  return msg;
}

console.log(validuser("_username","Valid?"));
console.log(validuser("_username1","Invalid?"));
console.log(validuser(".username","Invalid?"));
console.log(validuser("username","Invalid?"));
javascript regex
2个回答
-1
投票

在创建正则表达式时,您可以使用https://regex101.com/来帮助自己。

那就是说,这是你的正则表达式:

function test(username) {
  const regex = new RegExp('^_{1}[A-Za-z\.]*$', 'i');

  // Alternative version considering @thomas points
  // const regex = new RegExp('^_[A-Za-z._]+$', 'i');
  
  return regex.test(username);
}

console.log(test('test'));
console.log(test('_test'));
console.log(test('_te.s.t'));
console.log(test('_teST'));
console.log(test('Test_'));
console.log(test('^zdq^dz.'));
console.log(test('_teS/T'));
console.log(test('_9901A'));
enter image description here

-1
投票

你所描述的将是^_[a-zA-Z._]+$

  • ^意味着字符串的开头
  • _字面意思是你的下划线
  • [a-zA-Z._]+是低,高,点和下划线1次或更多次
  • $是字符串的结尾

但它允许__和_。作为用户名

const regex = /^_[a-zA-Z._]+$/gm;
const str = `_username

_username1

.username

username`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        document.write(`Found match, group ${groupIndex}: ${match}`);
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.