Search code examples
c#jqueryregexasp.net-mvc-5validationattribute

MVC5 ModelClientValidationRegexRule always failing


In my custom validation attribute I Have the following:

yield return new ModelClientValidationRegexRule(_invalidCharactersErrorMessage, "/^[A-Za-z0-9\\s]+$/i");

It is suppose to accept only letters, numbers and spaces. Now on the HTML side of things, here is what gets generated:

<input data-val="true" data-val-regex="Only letters, numbers, and spaces are allowed" data-val-regex-pattern="/^[A-Za-z0-9\s]+$/i" data-val-required="Alias is required" id="Alias" name="Alias" placeholder="Alias" type="text" value="" >

When I type in the field, it always gets activated and I see the error message no matter what I type in. Is my regex wrong or is there something else at play here? From what I've read online, my regex seems to be correct


Solution

  • Acc. to this resource, the value you pass inside data-val-regex-pattern is a string pattern, not a regex object, and it is already anchored.

    So, since you already added lowercase ASCII letters to your character class, you can just use

    yield return new ModelClientValidationRegexRule(_invalidCharactersErrorMessage, "[A-Za-z0-9\\s]+");
    

    or (since doubling ^ and $ does no harm), you may also try "^[A-Za-z0-9\\s]+$"