JavaScript验证注册表格

问题描述 投票:0回答:2

validateForm函数起作用。 validateEmail函数也可以正常工作,但要分开工作。如何将电子邮件的数据验证合并到validateForm函数中?换句话说,当字段为空且不满足要求时,如何使表单返回false?

  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 );
  }
javascript forms validation registration
2个回答
0
投票

您只需要将代码合并为一个函数

  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;
  }

0
投票

仅在validateForm内这样称呼validateEmail:

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 );
}

或者您可以将这些功能合并到@Addis的类似答案中

© www.soinside.com 2019 - 2024. All rights reserved.