Search code examples
activerecordjquery-validatecastle-monorail

ValidateRegExp client-side vs server-side issue


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.


Solution

  • 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.