Reputation: 201
Basically I am trying to write some code to use for form validation, Im quite new to this but am managing ok I think? My issue is basically this, I have created 3 validation methods for the 3 inputs i have in my form but im not quite sure how i go about adding all 3 methods to the one button click?
my code so far is:
function validation() {
function validateName() {
console.log("reaching here");
var name = document.getElementById("full_name");
if (name.value.length == 0) {
document.getElementById("okName").className = "fail";
}else{
document.getElementById("okName").className = "success";
}
}//End of validate name
function validateEmail() {
var email = document.getElementById("email");
if (email.value.length == 0) {
document.getElementById("okEmail").className = "fail";
}else{
document.getElementById("okEmail").className = "success";
}
}//end of validate email
function validatePhone() {
var phone = document.getElementById("phone");
if (phone.value.length == 0) {
document.getElementById("okPhone").className = "fail";
}else{
document.getElementById("okPhone").className = "success";
}
}//End of validate phone
}//End of validation function
I also tried removing all the validation methods from individual functions and just had them in one single fnction but this wouldnt work either? if anyone could shed some light on where im going wrong it would be great! Cheers in advance!
Upvotes: 0
Views: 780
Reputation: 47667
Try to attach an onclick()
event to your submit button - http://jsfiddle.net/zWrUM/
<button onclick="validation();">validate</button>
<script>
function validation() {
var name = document.getElementById("full_name");
if (name.value.length == 0) {
document.getElementById("okName").className = "fail";
alert("error 1");
return false;
}else{
document.getElementById("okName").className = "success";
}
var email = document.getElementById("email");
if (email.value.length == 0) {
document.getElementById("okEmail").className = "fail";
alert("error 2");
return false;
}else{
document.getElementById("okEmail").className = "success";
}
var phone = document.getElementById("phone");
if (phone.value.length == 0) {
document.getElementById("okPhone").className = "fail";
alert("error 3");
return false;
}else{
document.getElementById("okPhone").className = "success";
}
alert("success")
}//End of validation function
</script>
Upvotes: 1