Search code examples
jqueryasp.netasp.net-mvcjquery-pluginscustomvalidator

ASPNET MVC 3 unobstrusive and client side validation not working with placeHolder jQuery plugin


I'm trying to use unobstrusive validation with ASPNET MVC 3 project and placeHolder jQuery plugin like this:

[StringLength(20)]
[OnlyNumbersValidation(ErrorMessage = " ")]
[DisplayName("Fax n°")]
public string Fax { get; set; }

@Html.TextBoxFor(model => model.Fax, new { @class = "txt-input", placeholder = "Eg. Fax n°", maxlength = 31 })
@Html.ValidationMessageFor(model => model.Fax, "*", new { @class = "redtxt" })


public class OnlyNumbersValidationAttribute : RegularExpressionAttribute, IClientValidatable
{
    public OnlyNumbersValidationAttribute()
        : base(@"^\d+$")
    {
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        {
            var errorMessage = FormatErrorMessage(metadata.GetDisplayName());

            yield return new OnlyNumbersValidationRule(errorMessage);
        }
    }

    public class OnlyNumbersValidationRule : ModelClientValidationRule
    {
        public OnlyNumbersValidationRule(string errorMessage)
        {
            ErrorMessage = errorMessage;
            ValidationType = "digits";
        }
    }
}

The problem is the interaction between MVC 3 and placeHolder plugin, since if I enter no value (and the placeHolder is shown with the text "Eg. Fax n°" it "thinks" that I entered an invalid input because that text is composed with letters and not only numbers.

Any idea how to fix it?

Thanks in advance! Guillermo.


Solution

  • Fixing an error which involved having nested forms in an html page, and moving the custom validator to another class fixed the problem. Thanks.