1

I'm trying to use the "RegularExpression" DataAnnotation validaiton in my model. My problem is even for the valid input I provide for the field containing the validation, the regex doesn't match and it fails. I try to test the same valid input with the regex in a stand-alone console app and I find it gets through.

My point is, when regex is being used in dataannotation as validation, it considers all input as bad input. What am I missing here?

My regex is for checking comma-seperated email IDs. Here is my model:

 public partial class BuildModel 
{
    public Int64 ConfigID { get; set; }

    [Required(ErrorMessage = "Please select a stream!")]
    public String Name{ get; set; }



    [RegularExpression(@"^(([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)(\s*(;|,)\s*|\s*$))", ErrorMessage = "Please enter valid email IDs separated by commas")]
    public string EmailIDs { get; set; }

   public bool IsActive { get; set; }
}

Note: The "Required" data-annotation validation works just fine. It is just the Regex one, that won't work!

2 Answers 2

1

As far as i understand you just have problem within your Regex.

To validate emails separated by comma you can use this regex:

^( *[\w+-.%]+@[\w-.]+\.[A-Za-z]{2,4}( *, *)? *)+$

Check in in here.

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

4 Comments

Turns out this works in my app! I'm still not sure why the original regex would work in a console app but not in my app. Also, the rege that you've provided doesn't allow spaces at the start of each of the e-mail IDs. I need a regex to allow valid comma separated e-mail IDs (and allow spaces at the start or end of the mail IDs!!)
@Ponni i updated regex ant link to allow spaces. About your console app you should show how you use it there. MVC validation uses Regex.IsMatch method under the hood.
Thank you. However, this forces my string to have a space after the comma. It needs to be optional. Spaces may/may not be present.
@Ponni it works in both cases. With or without spaces before and after comma
0

You must the jquery.validate.min.js and jquery.validate.unobtrusive.min.js in your page without these libraries required annotation would not works.

3 Comments

yes, they are included, which is why the "Required" validations seems to work. It is just the "Regex" validation that I cannot get to work for some weird reason.
Use the built-en [EmailAddress] attribute, that will works fine.
Thanks. These were loading for me in dev, but not in production.

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.