简体   繁体   中英

Asp.Net MVC and custom unobtrusive validation

I'm trying to get a custom rule "mustbetrue" working. Based loosely on this question : My issue is that when I submit the form the client side validation doesn't give me an error (doesn't make the validation text appear). In addition I've put a break point in the jscript validation method and it never gets fired. The wireup code that adds the adapter does get fired. No errors in the console.

What am I doing wrong?

This is what I have server-side:

public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable
{
    public override bool IsValid(object value)
    {
        if (value == null) return false;
        try
        {
            return Convert.ToBoolean(value);
        }
        catch (InvalidCastException)
        {
            return false;
        }
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata,
                                                                           ControllerContext context)
    {
        yield return new ModelClientValidationRule
            {
                ErrorMessage = this.ErrorMessage,
                ValidationType = "mustbetrue"
            };
    }
}

and

public class MustBeTrueAttributeAdapter : DataAnnotationsModelValidator<MustBeTrueAttribute>
{
    public MustBeTrueAttributeAdapter(ModelMetadata metadata, ControllerContext context, MustBeTrueAttribute attribute)
        : base(metadata, context, attribute)
    {
    }

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        return new[] { new ModelClientValidationMustBeTrueRule(ErrorMessage) };
    }
}

public class ModelClientValidationMustBeTrueRule : ModelClientValidationRule
{
    public ModelClientValidationMustBeTrueRule(string errorMessage)
    {
        ErrorMessage = errorMessage;
        ValidationType = "mustbetrue";
    }
}

and in the global.asax

    protected void Application_Start()
    {
        // stuff
        DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MustBeTrueAttribute), typeof(MustBeTrueAttributeAdapter));
        // stuff
    }

and on the object:

[MustBeTrue(ErrorMessageResourceName = "Register_TermsNotAccepted", ErrorMessageResourceType = typeof(Resources.Global))]
public bool AcceptedTerms { get; set; }

client side:

$(document).ready(function () {
    jQuery.validator.addMethod("mustbetrue", function (value, element) {
        if (!this.depend(param, element))
            return "dependency-mismatch";
        return element.checked;
    });
    jQuery.validator.unobtrusive.adapters.addBool("mustbetrue", "mustbetrue");
});

and the relevant HTML that is output:

<input data-val="true" data-val-mustbetrue="You must accept the terms and conditions" data-val-required="The AcceptedTerms field is required." id="AcceptedTerms" name="AcceptedTerms" type="checkbox" value="true" class="valid">

如果您已经检查了是否启用了客户端验证(无论是在配置中还是在代码中),那么我想这是因为您是不干扰验证脚本解析html 之后添加适配器的 请参阅我的答案以获取详细信息和可能的选项

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM