javascript validation of single quotes
我的注册表中有一个密码字段。下面是JavaScript验证的代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | if(document.getElementById('txtPassword').value == '' || document.getElementById('txtPassword').value == 'Password' ){ alert("Please enter Password"); document.getElementById('txtPassword').focus(); return false; } else if (document.getElementById('txtPassword').value.length < 8) { alert('Please ensure your password has at least eight characters, a mix of upper and lowercase and at least one number'); return false; } else if ( (! document.getElementById('txtPassword').value.match(/[a-z]/) ) || (! document.getElementById('txtPassword').value.match(/[A-Z]/) ) ) { alert('Please ensure your password has at least eight characters, a mix of upper and lowercase and at least one number'); return false; } else if (!document.getElementById('txtPassword').value.match(/\d+/)) { alert('Please ensure your password has at least eight characters, a mix of upper and lowercase and at least one number'); return false; } else if (document.getElementById('txtPassword').length < 8) { alert('Please ensure your password has at least eight characters, a mix of upper and lowercase and at least one number'); return false; } |
我需要检查一下单引号。如果用户在密码字段中输入单引号并点击输入,则应弹出错误"在此字段中避免单引号"。
怎么做?
1 2 3 4 | else if (document.getElementById('txtPassword').value.indexOf("'") != -1) { alert("Avoid single quotes in this field"); return false; } |
这里是一个简单的测试用例。如果您制作了一个HTML页面,将它放在head标签中,在浏览器中打开它,您会看到它工作正常:
1 2 3 4 5 6 7 8 9 10 | var value1 ="abc'def"; var value2 ="abcdef"; if(value1.indexOf("'") != -1) alert(value1 +" contains a '"); else alert(value1 +" does not contain a '"); if(value2.indexOf("'") != -1) alert(value2 +" contains a '"); else alert(value2 +" does not contain a '"); |
号
使用此regex进行密码检查
1 | ^(?=.*\d)(?=.*[a-zA-Z]).{8,} |
目前,您正在进行大量的验证检查,以避免使用上面的regex。
1 2 3 4 5 6 7 8 9 | if (! /^(?=.*\d)(?=.*[a-zA-Z]).{8,}/.test(txtPass)) { flag = false; } else if(txtPass.indexOf("'") != -1) { flag = false; } if (!flag) alert("Please ensure your password has at least eight characters, a mix of upper and lowercase and at least one number"); |
。
参考现场演示