在javascript函数中调用正则表达式

时间:2012-10-03 11:27:17

标签: javascript expression

我花了很多时间试图解决这个问题。我知道这很容易,但它对我不起作用!

我想使用此表达式^.*(?=.{6,})(?=.*[a-zA-Z])[a-zA-Z0-9]+$使用javascript验证密码。

我不确定如何构造函数以及如何在代码中调用它。我有一些工作来验证电子邮件,但我无法使密码表达工作。

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 address")
       document.myForm.email.focus() ;
       return false;
   }
   return( true );
}

function validate()
{
    if( document.myForm.email.value == "" )
       {
         alert( "Please provide your Email!" );
         document.myForm.email.focus() ;
         return false;
       }
    else
       {
         // Put extra check for data format
         var ret = validateEmail();
         if( ret == false )
         {
            return false;
       }
}

我想从验证功能中调用passwordChecker。

2 个答案:

答案 0 :(得分:1)

这应该

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 address")
       document.myForm.email.focus() ;
       return false;
   }
   return true;
}

function validatePassword()
{     
   var reg = /^.*(?=.{6,})(?=.*[a-zA-Z])[a-zA-Z0-9]+$/;
   return reg.test(document.myForm.password.value);       
}

function validate()
{
    if(document.myForm.email.value == "" || !validateEmail())
    {
         alert( "Please provide a valid Email!" );
         document.myForm.email.focus() ;
         return false;
    }
    else if(!validatePassword())
    {
         alert("Please provide a valid password!");
         document.myForm.password.focus() ;
         return false;
    }
    return true;
}

答案 1 :(得分:0)

我的建议

function isEmail(email) {     
   var re = /^.*(?=.{6,})(?=.*[a-zA-Z])[a-zA-Z0-9]+$/; 
   return re.test(email); 
}

function validate() {
    var email = document.myForm.email;
    if (email.value.trim() =="") { // may need IE support
      alert( "Please provide your Email!" );
      email.focus() ;
      return false;
    }
    if (!isEmail(email.value)) {
      alert( "Please provide a valid Email!" );
      email.focus() ;
      return false;
    }
    return true;
}