How to use onClick ONLY if the email input field is valid?

Here is the code:

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

How to check and run the JS function only if the email is valid (validation using a user agent, no additional checks)?

UPDATE New browsers can independently check the input = email, there are also pseudo-classes: valid and: invalid. I need to run the function only if the browser "knows" that the letter is valid.

+5
source share
4 answers

You can use .checkValidity()input element method ( ). , , . , :

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

:

<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");
}
+10

, , omgemailgone():

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

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

}

( jQuery)

+1

JavaScript? if omgemailgone ( , )

:

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

+1

u , true false JavaScript?

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

This is a quick fix, I recommend you do it right without using inline onclick js

0
source

All Articles