Validate 2 regular expressions in a

5

I have the following regular expression

/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i

To validate emails, I must also validate that the email does not contain the word "notiene" and the expression is /^((?!notiene).)*$ , however I can not mix the two.

    
asked by sioesi 28.03.2018 в 16:24
source

1 answer

11

The problem . The negative inspection ( negative lookahead ) that you are using, starts from the beginning of the text, and consumes each of the characters as long as they are not followed by notiene

/^((?!notiene).)*$/

This means that when you try to validate the mail, you will find it at the end of the text. That is, the .* of that pattern already consumed all the characters, without allowing there to be more to validate.

The solution . On the other hand, if it is validated from the beginning of the text, but no character is consumed, then more than one subpattern can be validated:

/^(?!.*notiene)expresión2$/i

An inspection attempts to match the subpattern and, after matching, the cursor follows from the same position it was in before attempting such an inspection. It can be thought of as a construction that only returns true / false, but the rest of the regex can continue as if nothing had happened ( if it returned true, of course ).

With ^(?!.*notiene) we make sure that the whole line is crossed. If .*notiene does not match, being a negative inspection then it is like returning " true ", but we are still at the beginning of the text (no character was consumed) , and we can verify any other pattern from there.


Complete Regex: (using the response from Validate an email in JavaScript )

/^(?!.*notiene)(?:[^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*|"[^\n"]+")@(?:[^<>()[\].,;:\s@"]+\.)+[^<>()[\]\.,;:\s@"]{2,63}$/i


Demo:

document.getElementById('email').addEventListener('input', function(evt) {
    campo = evt.target;
    valido = document.getElementById('emailOK');
        
    emailRegex = /^(?!.*notiene)(?:[^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*|"[^\n"]+")@(?:[^<>()[\].,;:\s@"]+\.)+[^<>()[\]\.,;:\s@"]{2,63}$/i;
    //Se muestra un texto a modo de ejemplo
    if (emailRegex.test(campo.value)) {
      valido.innerText = "válido";
    } else {
      valido.innerText = "incorrecto";
    }
});
Email que no tenga "notiene":
<input id="email">
<span id="emailOK"></span>


General case

For any case where we have 2 regular expressions anchored at the beginning of the text (yes, they have to match from the beginning), be ^re1 and ^re2 , the way to verify both is :

/^(?=re1)re2/

Or, as in your case, that does not match the first one, but the second one does:

/^(?!re1)re2/


For example, joining 3 expressions: that has an upper case, that does not end in "1234" and that has between 8 and 200 characters .

/^(?=.*[A-ZÁÉÍÓÚÜÑ])(?!.*1234$).{8,200}$/
    
answered by 28.03.2018 / 16:45
source