Home > OS >  How to make if email is valid to start a function and if it's invalid to start other function i
How to make if email is valid to start a function and if it's invalid to start other function i

Time:09-11

I need to do an email input and button, and if it is valid to open a successful registration pop-up with adding style to it, but if the email input is empty or invalid to open an error pop-up. I don't know why, but the If, Else statement doesn't work and when I press the button nothing happens

Here is my code input code in HTML

<input name="email"  type="email" placeholder="Enter your email" required>
<button type="button"  >Register</button>


<script>
var testEmail = /^[A-Z0-9._% -] @([A-Z0-9-] \.) [A-Z]{2,4}$/i;
if (testEmail.test(valueToTest))
 {
  $(document).ready(function(){
  $(".3x").click(function(){
  $(".3X").css("display", "block");
  });}); 
 }
else
 {
  $(document).ready(function(){
  $(".3x").click(function(){
  $(".2rr").css("display", "block");
  });});
 }
</script>

CodePudding user response:

There are many problems with your code, consider using only once $(document).ready and $(".3x").click(function(){.

On a side note, not sure what elements are these: $(".3X"), $(".2rr") but since classnames start with a number, CSS cannot be applied to them (unless you escape the number, see this: https://stackoverflow.com/a/45293575/5334486)

$(document).ready(function() {

  const testEmail = /^[A-Z0-9._% -] @([A-Z0-9-] \.) [A-Z]{2,4}$/i;

  $(".3x").click(function() {
    const valueToTest = $('input[type="email"]').val()

    if (testEmail.test(valueToTest)) {
      console.log("Email is valid.");
      $(".3X").css("display", "block");
    } else {
      console.log("Email IS NOT valid.");
      $(".2rr").css("display", "block");
    }
  })

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="email"  type="email" placeholder="Enter your email" required>

<button type="button" >Register</button>

  • Related