有人建議使用Regular Expressions 來檢查input資料,於是就去找了一些SourceCode,
以下是第一個可以正確執行無誤的範例
=== login.jsp ===
<title>Login</title>
<script type="text/javascript">
var RE_EMAIL = /^(\w+[\-\.])*\w+@(\w+\.)+[A-Za-z]+$/;
var RE_PASSWORD = /^[A-Za-z\d]{6,8}$/;
function validate(form){
var email = form.Email.value;
var password = form.Password.value;
var errors = [];
if (!RE_EMAIL.test(email)) {
errors[errors.length] = "You must enter a valid email address.";
}
if (!RE_PASSWORD.test(password)) {
errors[errors.length] = "You must enter a valid password.";
}
if (errors.length > 0) {
reportErrors(errors);
return false;
}
return true;
}
function reportErrors(errors){
var msg = "There were some problems...\n";
for (var i = 0; i<errors.length; i++) {
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}
</script>
<h1>Login Form</h1>
<form method="post" action="main.jsp" onsubmit="return validate(this);">
Email: <input type="text" name="Email" size="25"><br/>
Password: <input type="password" name="Password" size="10"><br/>
*Password must be between 6 and 10 characters and
can only contain letters and digits.<br/>
<input type="submit" value="Submit">
<input type="reset" value="Reset Form">
</form>