Zachary Scott
Zachary Scott

Reputation: 21182

ASP.NET MVC 2 Data Validation: Make C# Regex work for both C# and JavaScript simultaneously?

I have this C# regex:

^\s?((?<qty>\d+)\s?/)?\s?[$]?\s?(?<price>\d{0,2}(?:\.\d{1,2})?)\s?$

and use MVC's data validation at the client. JavaScript says this regex is invalid, although C# works perfectly fine. Any idea how to get it to work for both C# and JavaScript, since it doesn't seem possible to provide a separate JavaScript Regex in the Data Validation annotations?

The regex validates a quantity and price. 4/$2.69 for example.

Upvotes: 0

Views: 533

Answers (2)

SLaks
SLaks

Reputation: 887469

Remove the group names (<qty>).

Upvotes: 1

kennytm
kennytm

Reputation: 523344

Javascript does not support named reference (?<…>…). You need to use

^\s?((\d+)\s?/)?\s?[$]?\s?(\d{0,2}(?:\.\d{1,2})?)\s?$

and refer qty and price as 1 and 2 instead.

Upvotes: 2

Related Questions