简体   繁体   中英

Asp.Net Model validation with Regex. Looking for specific string not just a letter

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.")]

Result using the gmail format

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" ".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM