开发者

Conditional Regular Expression testing of a CSV

I am doing some client side validation in ASP.NET MVC and I found myself trying to do conditional validation on a set of items (ie, if the checkbox is checked then validate and visa versa). This was problematic, to say the least.

To get around this, I figured that I could "cheat" by having a hidden element that would contain all of the information for each set, thus the idea of a CSV string containing this information.

I already use a custom [HiddenRequired] attribu开发者_如何学Gote to validate if the hidden input contains a value, with success, but I thought as I will need to validate each piece of data in the csv, that a regular expression would solve this.

My regular expression work is extremely weak and after a good 2 hours I've almost given up.

This is an example of the csv string:

true,3,24,over,0.5

to explain:

  • true denotes if I should validate the rest. I need to conditionally switch in the regex using this
  • 3 and 24 are integers and will only ever fall in the range 0-24.
  • over is a string and will either be over or under
  • 0.5 is a decimal value, of unknown precision.

In the validation, all values should be present and at least of the correct type

Is there someone who can either provide such a regex or at least provide some hints, i'm really stuck!


Try this regex:

@"^(true,([01]?\d|2[0-4]),([01]?\d|2[0-4]),(over|under),\d+\.?\d+|false.*)$"

I'll try to explain it using comments. Feel free to ask if anything is unclear. =)

@"
  ^             # start of line
   (
     true,                # literal true
    ([01]?\d              # Either 0, 1, or nothing followed by a digit
        |                 # or
     2[0-4]),             # 20 - 24
    ([01]?\d|2[0-4]),     # again
    (over|under),         # over or under
    \d+\.?\d+             # any number of digits, optional dot, any number of digits

   |           #... OR ... 

     false.*              # false followed by anything
   )
  $            # end of line
");


I would probably use a Split(',') and validate elements of the resulting array instead of using a regex. Also you should watch out for the \, case (the comma is part of the value).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜