在将代码提交到服务器之前,我在代码中添加了一个 javascript 表单验证。当用户点击submit
它应该在提交之前调用 javascript 验证器。如果验证者同意,那么它才应该提交。我似乎做错了什么,因为无论验证者说什么,它都会提交......
html:
<form id="start_form" method="post" onsubmit="return validate_form(this);">
<ul class="error">
</ul>
<label for="title" >Title: </label><input value="{{ post.title }}" type="text" name="title">
<label for="summery" >Summery/Prompt: <textarea name="summery">{{ post.summery }}</textarea>
<label for="person">Participants Emails: </label>
<ul id="people">
<li><input type="text" name="person1"></li>
<li><input type="text" name="person2"></li>
</ul>
<a href="javascript:void(0)" onclick="add_group();"><img class="img_button" width="30px" height="30px" src="{{ STATIC_URL }}Image/plus_button.png" /></a>
<a href="javascript:void(0)" onclick="remove_group();"><img class="img_button" width="30px" height="30px" src="{{ STATIC_URL }}Image/minus_button.png" /></a>
<button type="submit" class="button">Start Game</button>
<input type="hidden" id="pn" name="pn" value="2">
</form>
Javascript函数:
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function append_error(m) {
c = "<li>" + m + "</li>"
$('#error').appendChild(c)
}
function validate_form(form) {
var e = true
if (form.title.value == "") {
append_error("Title Required");
e = false
}
if (form.summery.value == "") {
append_error("Summery Required");
e = false
}
for (i = 0; i < Number(form.pn.value); i++){
email = $('[name="person"' + i++ + '"]').innerText
if(email == ""){
append_error("Email #" + ++i + " can not be blank")
e = false
} else if (!validateEmail(email)) {
append_error("Email #" + i++ + " is not valid")
e = false
}
}
return e;
}