views:

18

answers:

2

I'm using monorail, activerecord, and jquery. I have a form with a zip code textbox. I have in my active record class associated to the form:

[Property]
        [ValidateNonEmpty]
        [ValidateRegExp(@"/^\d{5}(-\d{4})?$/", "Invalid")]
        public string ZipCode { get; set; }

As you can see, I'm using the ValidateRegExp attribute, which then auto-generates jQuery validate rules. The issue is that regular expressions are different in javascript than they are in C#. Javascript requires a / before and after the regex, whereas C# does not. If I put the slashes then the jQuery validation will work, but if they bypass the javascript validation and submit the form with js disabled (or if someone saves the object through another means like a test case) then it'll say the zip code is invalid because C# doesn't like the slashes.

So my question is, how do you please both javascript and C# with one regex? I would expect it to be smart enough to add slashes before and after just for the jQuery validation so that you could specify the regex in C# without the slashes but this is not the case it seems.

+1  A: 

You should be specifying the regular expression itself, without the surrounding / characters.

If you are having problems with the client side, it would help if you'd include the JS error you see (if any), and actual generated JS code on the page that is being written out by Monorail to your page, and also the version of Monorail you are using.

As a side note, lets look at the code generating the JS validation rule from the validation attribute in JQueryValidator.cs

the relevant piece is at line 378 (as of current version of the codebase):

           "function(value, element, param) { return new RegExp(param).test(value); }" 

which points to the fact that the new RegExp(expression) is used, rather than the /expression/ format. With that - it is clear that Monorail's jquery validator integration is ok.

Ken Egozi
A: 

I'm using jQuery 1.4.2. Not sure what version of MonoRail I'm using, the Castle.MonoRail.Framework dll says v2.0.0.0. I updated it within the last 3 months though so it's fairly new. The js that you're showing indicates that you have an even newer version than me, as it generates the following for me (if no slashes included in the ValidateRegExp expression):

"user.username":{ required: true , regExp: ^[\w ]{4,50}$ }

This obviously gives a syntax error in js, as it's not wrapped in quotes or slashes. I ended up creating a new RegExp validator with AbstractValidator as the base class to get around the faulty one that is in my version of MonoRail.

Do you know if this was an issue that was fixed in the last couple of months? Otherwise I can't explain how yours generates new RegExp in js and mine does not...

Justin