Reputation: 380
I am currently in a situation where we do not want to allow outside emails for one of our applications. The application is developed in Asp.Net MVC. I am aware that on the model side you can do server side validation which you can then use to get front end validation. My problem is that the RegularExpression I use always returns true as if it is only looking for one of those letters not the whole string. How can I make it look for the whole string?
Here is an example code snippet and result.
[Required]
[EmailAddress]
[Display(Name = "Email")]
//I have tried many different variations on the regex
[RegularExpression("{/@gmail}", ErrorMessage = "No Gmail accounts allowed")]
//[RegularExpression("{[/@gmail]}", ErrorMessage = "No Gmail accounts allowed")]
//[RegularExpression("{[/@][g][m][a][i][l]}", ErrorMessage = "No Gmail accounts allowed")]
//[RegularExpression("/@gmail", ErrorMessage = "No Gmail accounts allowed")]
public string Email {get; set;}
This seems to be the result no matter what variation I try on the regex. I also read through all the rules and I didn't see anything for matching a string. Result
Very stumped.... In perl it would be as simple as "s/@gmail//g", is there nothing similar that can be done from the model side?
@PeterB
[RegularExpression("@gmail", ErrorMessage = "Please do not use your gmail account.")]
Upvotes: 3
Views: 2917
Reputation: 28305
Based on your original understanding, the answer would have been to use:
[RegularExpression("@gmail", ErrorMessage = "No Gmail accounts allowed")]
However, this validation rule actually states that the email must contain "@gmail"
, not must not contain.
The solution, then, is to use a negative lookahead to negate the pattern - something like:
[RegularExpression("^(?!.*@gmail)", ErrorMessage = "No Gmail accounts allowed")]
This is saying "looking ahead from the start of the string, it cannot contain the pattern: "@gmail"
".
Upvotes: 3