jeny
jeny

Reputation: 387

I am unable to show any message after successful validation In JavaScript

I am unable to show any message after successful validation in JavaScript, and I am going wrong in the end if Statement. I want to display we will get back to you after it passes validation.

<script>
function validateForm() {
    var x = document.forms["myForm"]["fname"].value;
    if (x.length < 10) {
        window.alert("The field cannot contain more than 10 characters!");
        return false;
    }
}
function validateForm() {
    var k = document.forms["myForm"]["query"].value;
    if (k.length < 25) {
        window.alert("The field cannot contain atleast 25 characters!");
        return false;
    }
}
function validateForm() {
    var k1 = document.forms["myForm"]["email"].value;
    var atpos = k1.indexOf("@");
    var dotpos = k1.lastIndexOf(".");
    if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= k1.length) {
        alert("Not a valid e-mail address");
        return false;
    }
    if (k1.length < 10) {
        window.alert("The field cannot contain atleast 25 characters!");
    }
}
if (x && k && k1 !== true) {
    this.x = x;
    this.k = k;
    this.k1 = k1;
    window.alert("We will get back to you");
}
</script>  

Upvotes: 0

Views: 37

Answers (1)

Mihai Matei
Mihai Matei

Reputation: 24276

function validateForm() {
  var isValid = true;
  var x = document.forms["myForm"]["fname"].value;
  if (x.length < 10){
     window.alert("The field cannot contain more than 10 characters!");
     isValid = false;
  }

  var k = document.forms["myForm"]["query"].value;
  if (k.length<25) {
     window.alert("The field cannot contain atleast 25 characters!");
     isValid = false;
  }

  var k1= document.forms["myForm"]["email"].value;
  var atpos = k1.indexOf("@");
  var dotpos = k1.lastIndexOf(".");
  if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= k1.length) {
     alert("Not a valid e-mail address");
     isValid = false;
  }
  if (k1.length < 10) {
     window.alert("The field cannot contain atleast 25 characters!");
     isValid = false;
  }
  if (!isValid) {
     // you should take a look here.. what do you want to achieve?
     this.x = x;
     this.k = k;
     this.k1 = k1;
     window.alert("We will get back to you");
  }
  return isValid;
}

your form should use the onsubmit attribute:

<form onsubmit="return validateForm()"></form>

Take a look at http://jqueryvalidation.org/documentation/ . You may consider starting to learn jQuery or another js framework.

Upvotes: 1

Related Questions