Javascript 使用if语句检查用户名中字母和数字的组合
他昨天说。我正在使用JavaScript编写客户端表单验证,并在代码中使用了一组if语句 就是这样Javascript 使用if语句检查用户名中字母和数字的组合,javascript,forms,validation,if-statement,Javascript,Forms,Validation,If Statement,他昨天说。我正在使用JavaScript编写客户端表单验证,并在代码中使用了一组if语句 就是这样 function validateloginform() { //login page validation test // var username = document.forms["form"]["username"].value; var password = document.forms["form"]["password"].value; var verifyp
function validateloginform() { //login page validation test //
var username = document.forms["form"]["username"].value;
var password = document.forms["form"]["password"].value;
var verifypassword = document.forms["form"]["verifypassword"].value;
if (document.form.username.value == null || document.form.username.value == "") {
alert("Username is blank...it must be entered");
document.form.username.focus();
return false;
}
if (document.form.username.value.length != 8) {
alert("Username must be 8 characters long");
document.form.username.focus();
return false;
} else {
alert("Correct");
return true;
}
}
我如何才能更具体地使用我的语句来包含数字和字母([a-z]或[0-9])字符的组合
如果用户名或密码不包含字母和数字的组合,则返回false。还有,有没有办法包括特殊字符?
查看该链接,了解Javascript正则表达式教程。下面是一个例子(来自教程,但我添加了一些解释),如果你想切入正题
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
// Create a regular expression
// This regular expression is used to check the user's input phone number is in
// a common phone number format.
var re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/;
function testInfo(phoneInput){
// The exec() call below checks if the phoneInput.value matches the regex re
// which was defined above.
var OK = re.exec(phoneInput.value);
// OK will be true or false depending on if phoneInput.value matched the regex.
if (!OK)
window.alert(RegExp.input + " isn't a phone number with area code!");
else
window.alert("Thanks, your phone number is " + OK[0]);
}
</script>
</head>
<body>
<p>Enter your phone number (with area code) and then click "Check".
<br>The expected format is like ###-###-####.</p>
<form action="#">
<input id="phone"><button onclick="testInfo(document.getElementById('phone'));">Check</button>
</form>
</body>
//创建正则表达式
//此正则表达式用于检查用户输入的电话号码是否在
//通用电话号码格式。
变量re=/(?:\d{3}\(\d{3}\)([-\/\.])\d{3}\1\d{4}/;
函数testInfo(电话输入){
//下面的exec()调用检查phoneInput.value是否与正则表达式re匹配
//这是上面定义的。
var OK=re.exec(phoneInput.value);
//OK将是true或false,具体取决于phoneInput.value是否与正则表达式匹配。
如果(!OK)
window.alert(RegExp.input+“不是带区号的电话号码!”);
其他的
window.alert(“谢谢,您的电话号码是”+OK[0]);
}
输入您的电话号码(带区号),然后单击“检查”。
预期的格式类似于###-#-#-#
检查
可能的副本发布这么多关于用户(和密码)应该是什么样子的线索不是一个好主意。注册会有所不同,但就个人而言,我不会提供任何信息,除非表单上有错误。