使用js模式进行表单验证



编写程序从用户处获取密码作为输入。的密码必须符合以下要求:a.应包含字母和数字b.不应该以数字开头c.长度至少为8个字符d.如果密码不符合上述要求,则提示输入用户需要输入有效的密码。对于a-z字符码,所有,0 - 9

我使用下面的代码。不知道为什么模式总是假的

 const pattern = /([a - zA - Z][a - zA - Z0 - 9]{ 8, })/;
    
    const userInput = prompt('Enter Password');
    console.log(pattern.test(userInput));
    
    // while (!pattern.test(userInput)) {
    //   prompt("Please Enter valid password")
    // }
    
    alert('Correct password');

解决方案

const pattern = /^[0-9a-zA-Z]+$/;
const patternTwo = /^[0-9]+$/;
let userInput;
do {
  userInput = prompt("Please Enter valid password");
} while (!pattern.test(userInput) || userInput.length < 8 || patternTwo.test(userInput[0]));
alert('Correct password');

最新更新