Reft
Reft

Reputation: 2433

Regex MVC model Validation

This is a working regex script in JS:

var emailRegExp   = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;

How would I escape characters like \ and "

I would like to use it for my model validation like this:

[RegularExpression(@"/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/")]

But it fails when I escape with either two \ or using @ before the string.

How would this script look like in a C# model validation?

Thanks!

Upvotes: 0

Views: 134

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174696

You need to remove the js delimiter that is the the forward slash present at the start and the end.

@"^(([^<>()[\]\\.,;:\s@""]+(\.[^<>()[\]\\.,;:\s@""]+)*)|("".+""))@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$"

Upvotes: 1

Related Questions