昨天陈述了Javascript。我正在使用JavaScript编写客户端表单验证,并为我的代码使用了一堆if语句。
就是这样:
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。另外,有没有办法包含特殊字符?
答案 0 :(得分:0)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
使用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>