6

这是代码:

<input id="subscribe-email" type="email" placeholder="john.doe@example.com" />
            <button type="submit" id="subscribe-submit" onClick="javascript:omgemailgone();" />

仅当电子邮件有效(由用户代理验证,无需额外验证)时,如何检查和运行 JS 功能?

更新。新的浏览器可以自己验证input=email,也有伪类:valid 和:invalid。仅当浏览器“知道”该电子邮件有效时,我才需要运行功能。

4

4 回答 4

9

You can use the .checkValidity() method of the input element (in this case, the email input field). This will return a boolean indicating wether the input is valid or not. Here is a fiddle to play with:

http://jsfiddle.net/QP4Rc/4/

And the code:

<input id="subscribe-email" type="email" required="required" placeholder="john.doe@example.com" />

<button type="submit" id="subscribe-submit" onClick="check()">
click me
</button>

function check()
{
  if(!document.getElementById("subscribe-email").checkValidity())
  {

    //do stuff here ie. show errors
    alert("input not valid!");

  }else
  {
      callMeIfValid();
  }
}

function callMeIfValid()
{
  //submit form or whatever
  alert("valid input");
}
于 2013-03-21T21:51:40.133 回答
1

您可以使用正则表达式来检查您的电子邮件是否有效omgemailgone()

function omgemailgone (){
   var mail = $('#subscribe-email').val();

   //Example of regular expression
   if(mail.match(/YourRegexp/)
   {
      //Do stuff
   }
   else alert("Invalid e-mail");

}

(在这里使用 jQuery)

于 2013-03-21T16:57:01.550 回答
1

check Validate email address in JavaScript? for validation and then implement it into an if statement in your omgemailgone method (if valid continue, else do nothing)

edit:

function validateEmail(email) { 
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\
".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA
-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}

from the link

于 2013-03-21T16:57:44.020 回答
0

你需要一个验证电子邮件并返回真或假的函数 验证 JavaScript 中的电子邮件地址?

<button type="submit" id="subscribe-submit" onClick="javascript:validateEmail(document.getElementById('subscribe-email').value) ? omgemailgone() : alert('email is wrong dude');" />

这是一个快速的解决方案,我建议您正确执行,不要使用内联 onclick js

于 2013-03-21T16:57:43.433 回答