简体   繁体   中英

JavaScript Validation Registration Form

The validateForm function works. And the validateEmail function works as well but separately. How do I incorporate the data validation for the email in the validateForm function? In other words, how do I get the form to return false for when the fields are empty and requirements are not met?

  function validateForm() {

     if( document.myForm.userName.value == "" ) {
        alert( "Please provide your name!" );
        document.myForm.userName.focus() ;
        return false;
     }
     if( document.myForm.email.value == "" ) {
        alert( "Please provide your Email!" );
        document.myForm.email.focus() ;
        return false;
     }
     return( true );
  }

 function validateEmail() {
     var emailID = document.myForm.email.value;
     atpos = emailID.indexOf("@");
     dotpos = emailID.lastIndexOf(".");

     if (atpos < 1 || ( dotpos - atpos < 2 )) {
        alert("Please enter correct email ID")
        document.myForm.email.focus() ;
        return false;
     }
     return( true );
  }

You just have to merge your code into one function

  function validateForm() {

    var emailID = document.myForm.email.value;
    atpos = emailID.indexOf("@");
    dotpos = emailID.lastIndexOf(".");

     if( document.myForm.userName.value == "" ) {
        alert( "Please provide your name!" );
        document.myForm.userName.focus() ;
        return false;
     }
     if( document.myForm.email.value == "" ) {
        alert( "Please provide your Email!" );
        document.myForm.email.focus() ;
        return false;
     }
     if (atpos < 1 || ( dotpos - atpos < 2 )) {
        alert("Please enter correct email ID")
        document.myForm.email.focus() ;
        return false;
     }
     return true;
  }

just called validateEmail inside validateForm like this :

function validateForm() {

 if( document.myForm.userName.value == "" ) {
    alert( "Please provide your name!" );
    document.myForm.userName.focus() ;
    return false;
 }
 if( document.myForm.email.value == "" ) {
    alert( "Please provide your Email!" );
    document.myForm.email.focus() ;
    return false;
 }
 return validateEmail();
}

function validateEmail() {
 var emailID = document.myForm.email.value;
 atpos = emailID.indexOf("@");
 dotpos = emailID.lastIndexOf(".");

 if (atpos < 1 || ( dotpos - atpos < 2 )) {
    alert("Please enter correct email ID")
    document.myForm.email.focus() ;
    return false;
 }
 return( true );
}

or u can u merge those function into like answer from @Addis

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