2

guys, I don't know this question is already present or not but I have tried every search, so my question is why my regex is not working properly in RegularExpression attribute. this same regex I have used in javascript and this is working on javascript. can anyone help me what I am doing wrong here?

[Required]
[Display(Name = "First name")]
[MaxLength(50)]
[RegularExpression("^(?![@\\+\\-=\\*])", ErrorMessage = "First Name Should not start with these characters @, +, =, *, -")]
public string firstname { get; set; }

I am using this regex for validating the First Name should not start with @,+,=,*,-.

I have already spent 3 hours to figure out what I am doing wrong here.

Manish
  • 1,139
  • 7
  • 21
  • Take into account that those two have different regex engines, and you may encounter certain discrepancies. – Darjan Bogdan Jan 17 '18 at 07:35
  • 1
    What do you mean by `not working`? Did your validator not trigger on client side at all? or the regex is not validating as expected? – Zeeshan Jan 17 '18 at 07:36
  • 2
    Your Regex expression is failing. You can test Regex expressions here: http://regexstorm.net/tester – Oystein Jan 17 '18 at 07:37
  • @DarjanBogdan I have tested this regex using Regex class I think this is working on C# but I am using RegularExpression attribute for the first time so I don't know how it is work. – Manish Jan 17 '18 at 07:38
  • @Zeeshan is triggering but it's not working as I expected. it's not allowing anything . – Manish Jan 17 '18 at 07:39
  • @Oystein this website using js regex engine so please remove one \ then it will work. – Manish Jan 17 '18 at 07:41

2 Answers2

2

I believe you regex should look like this:

^(?![@\\+\\-=\\*]).*

Here is a working example.

teo van kot
  • 12,350
  • 10
  • 38
  • 70
0

Your regex is invalid. Here is the updated one, which works as you expected:

^(?![@\\+\-\\=\\*])
Zeeshan
  • 2,884
  • 3
  • 28
  • 47