简体   繁体   中英

Simple Javascript form validation code issue

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!

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>

您可以查看addEventListener和oldIE类似的方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM