bendeeeh
bendeeeh

Reputation: 33

Javascript functionality not working properly on my regex

I can't seem to figure out where in my code is wrong, if it is my regex or my code in javascript. When I input the correct email format, the alert is still coming when it is supposed to come out only when the email format is wrong.

I am using the toggleClass functionality of javascript for the alerts in an active modal.

$('.email').blur(function() {
  var regex =
    /^(([^<>()[\]\\.,;:\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,}))$/;
  var isEmailCorrect = $(this).val().match(regex);
  $('.modal:visible').find('.popemail').toggleClass('hide', isEmailCorrect);
  $('.sub').prop('disabled', !isEmailCorrect);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<label>Email</label>
<span id="popover-email" class="popemail hide pull-right block-help">
    <i class="fa fa-info-circle text-danger" aria-hidden="true"></i>
    Please use the proper format of an email</span>
<input type="email" class="email form-control" id="email" name="email" placeholder="Email" value="<?php echo $row['email']; ?>">

When an email is placed with proper format there should be no alert to come out, but when wrong format of email is placed then the alert should come out. I used toggle class for the alert, see line #4.

Upvotes: 0

Views: 89

Answers (3)

Chris Barr
Chris Barr

Reputation: 34032

You are using .match() which will return an array of matched substrings in your regex. This is not a boolean value. Run this example to see:

var regex =/^(([^<>()[\]\\.,;:\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,}))$/;

console.log("[email protected]".match(regex));

What you want instead if yo use .test() which will return a boolean if it matches or not.

var regex =/^(([^<>()[\]\\.,;:\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,}))$/;

console.log(regex.test("[email protected]"));
console.log(regex.test("banana"));


EDIT:

To be clear, this is what your code should be. I've added some debugging console.log calls to help you see what things are. I've changed the HTML a bit just to make this demo work. Click the "Run code snippet" button.

$('.email').blur(function() {
  var regex = /^(([^<>()[\]\\.,;:\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,}))$/;
  
  var isEmailCorrect = regex.test(this.value);
  
  console.log('Email Value:', this.value);
  console.log('Is Email Correct:', isEmailCorrect);
  
  $('.modal:visible').find('.popemail').toggleClass('hide', isEmailCorrect);
  $('.sub').prop('disabled', !isEmailCorrect);
});
.hide{display:none;}
.popover-email{color: red;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="modal">
  <label for="email">Email</label>
  <input type="email" id="email" class="email" name="email" placeholder="Email">
  <span id="popover-email" class="hide popemail">Please use the proper format of an email</span>
</div>

Upvotes: 3

dganenco
dganenco

Reputation: 1616

As mentioned by @Chris Barr you should use Regexp#test method instead of String#match. So you have to change only one row in your code:

  var isEmailCorrect = regex.test($(this).val()); 

After that you have to debug in console your jQuery selectors, because of using your html element with class 'modal' could not be found anymore.

Upvotes: 0

Emma
Emma

Reputation: 27723

Your original expression works just fine, maybe you might want to trim your inputs before testing it, might pass some spaces that would conflict with start and end anchors, or maybe you are passing some chars that are not allowed:

^(([^<>()[\]\\.,;:\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,}))$

Demo

const regex = /^(([^<>()[\]\\.,;:\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,}))$/gm;
const str = `[email protected]
[email protected]
alice@google_.com
[email protected]_
`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Upvotes: 0

Related Questions