1

I am using Asp.Net MVC 3 and I am adding a validator later in the lifecycle through jquery with jquery.validate using [this code][1]:

Thanks to the answer of redsquare I added a method like this:

$.validator.addMethod(
        "regex",
        function(value, element, regexp) {
            var check = false;
            var re = new RegExp(regexp);
            return this.optional(element) || re.test(value);
        },
        "Please check your input."
);

now all you need to do to validate against any regex is this:

$("Textbox").rules("add", { regex: "^[a-zA-Z'.\s]{1,40}$" })

The validation is working fine, but the actual message isn't showing up anywhere... what am I doing wrong? Thank you.

naspinski
  • 33,200
  • 34
  • 107
  • 157

3 Answers3

4

I had the same issue. Never found what was causing the issue and I've ended up using MVC unobtrusive validation by assigning validation attributes to my input fields :

so assuming you've got a #Textbox input :

<input class="text-box" id="Textbox" name="Textbox" type="text" value="">

Easy way to turn on the validation is just to assign data-val-* attributes :

$(document).ready(function(){
   $('#Textbox').attr('data-val','true'); // turn on validation
   $('#Textbox').attr('data-val-regex','The input does not match the validation pattern'); // message to show when validation fails
   $('#Textbox').attr('data-val-regex-pattern',"@^[a-zA-Z&#39;.\s]{1,40}$"); //regex
});

This is they way I do it on my website and it works. The way you call your validation may collide with they way how Microsoft implemented jQuery validator, however I couldn't find where that is

Paweł Staniec
  • 3,141
  • 3
  • 28
  • 41
2

Do you use it with mvc metamodel? If so, make sure you have the

@Html.ValidationMessageFor(m => m.obj)

just next to your text box

Hope this is what you mean :)

shennyL
  • 2,734
  • 10
  • 39
  • 64
0

Well, assuming the selector for your form and the validate function are set correctly, It should work correctly, is it maybe a problem with those? Posting the rest of the validation would be useful.

Jaibuu
  • 580
  • 3
  • 9