Reputation: 11493
I added a javascript form validation to my code, before submitting it to the server. When the user clicks submit
it should call the javascript validator before submitting it. If the validator gives the ok, only then should it submit. I seem to be doing something wrong, because it submits regardless of what the validator says...
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:
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;
}
Upvotes: 2
Views: 401
Reputation: 1574
It looks like you are using jQuery so you can bind the submit event like so:
$('#start_form').submit(function(){
return validate_form(this);
});
Upvotes: 0
Reputation: 2704
jquery doesn't have appendChild method. in your function:
function append_error(m) {
c = "<li>" + m + "</li>"
$('#error').appendChild(c)
}
this cause an error that submition eventually ignores your validation function
Upvotes: 2