Search code examples
jqueryregexregex-lookaroundsregex-group

Regex: Excluding combinations of characters and limiting certain characters in Regex / jQuery (partly working)


I am trying to validate an email input using Regex in jQuery - only for the following criteria:

Inputs I want to allow:

  • lowercase letters (multiple)
  • digits (multiple)
  • dots / periods (multiple)
  • dashes (multiple)
  • @ sign (only one)

Inputs I want to prevent:

  • dot / period, dash, @ sign at the beginning of the string
  • dot / period, dash, @ sign at the end of the string
  • two dots / periods OR two dashes in a row
  • a dot / period and a dash (or a dash and a dot / period) in a row

So far I came up with the following but I am having trouble with excluding the combinations of two symbols and with limiting the @ sign to only one.

Can someone show me how to do this right ?

Note:
I am only looking for a basic validation for the above criteria and for English letters only (everything else I cover in jQuery).

My Regex:

var val = $(this).val();
var checkEmail = /(?!^[@.-])(?!.*@@)(?!.*\.\.)(?!.*--)(?!.*[@.-]$)[0-9a-z@\.\-]/g;

if(val.match(checkEmail) {
   console.log('input valid');
   } else {
   console.log('input invalid');
}

Many thanks in advance,
Tom


Solution

  • You can use the regex below to achieve your results:

    ^(?!.+?(?:\.-|\.\.|--|-@|\.@|@\.).+?)[^.-@ ][a-z0-9_.-]+@[a-z0-9_.-]+(?<=[^.-@ ])$
    

    Explanation of the above regex:

    ^, $ - Represents start and end of test string resp.

    (?!.+?(?:\.-|\.\.|--|-@|\.@|@\.).+?) - Represents negative lookahead not matching the test string if it contains consecutive .-, .., --, -@, .@ or @..

    [^.-@ ] - Represents negative match if string starts with any of .-@.

    [a-z0-9_.-]+@[a-z0-9_.-]+ - Represents the character set where the String contains anything in the characters mentioned above with only one @ sign.

    (?<=[^.-@ ]) - Represents positive lookbehind which matches any test string not ending with .-@.

    You can find the demo of above regex here.

    IMPLEMENTATION IN JAVASCRIPT(JQUERY):

    var val = "hello@gmail.com";
    var checkEmail = /^(?!.+?(?:\.-|\.\.|--|-@|\.@|@\.).+?)[^.-@ ][a-z0-9_.-]+@[a-z0-9_.-]+(?<=[^.-@ ])$/gm;
    
    if (val.match(checkEmail)) {
      console.log('input valid');
    } else {
      console.log('input invalid');
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>