5

I am writing a regular expression(regex) for adding multiple email ids in an input box with following conditions:

  1. Multiple email ids must be separated with comma ,
  2. Need to have atleast one email id
  3. There should not be any whitespaces in input field.

So i created this regex:

^(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([,.](([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$

I tested it in regex101.com and its working like a charm https://regex101.com/r/bU7rU8/1

But when i integrate it with code, it works, but fails on leading and trailing whitespace.

Here is the demo link: http://jsfiddle.net/2G8gA/330/

2
  • 2
    Use ng-trim="false". Have a look at this fiddle. Is it what you need? Commented Aug 21, 2015 at 7:51
  • @stribizhev: You made my day. I am struggling to find out the issue from last 2hrs. Thanks for help. Please post an answer. I will accept it. :) Commented Aug 21, 2015 at 7:55

2 Answers 2

11

AngularJS trims the input by default, so you need to use ng-trim="false" in order to pass leading and trailing whitespace to your pattern regex.

See documentation:

ngTrim (optional)

If set to false Angular will not automatically trim the input. This parameter is ignored for input[type=password] controls, which will never trim the input.

(default: true)

Sign up to request clarification or add additional context in comments.

Comments

2

Do you want leading/trailing spaces allowed on the whole string, or around each individual address?

For the former your regex should be

/^(\s*([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([,.](([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+\s*)*$/

and for the latter

/^(\s*([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25}\s*)+([,.](\s*([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+\s*)*$/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.