使用IClientModelValidator验证

问题描述 投票:3回答:1

在之前的版本(RC1)中,我使用接口IClientModelValidator来验证/比较密码和使用'ModelClientValidationEqualToRule'类确认密码,如下所示

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ClientModelValidationContext context)
    {
        String strMsg = AccessLocalization.GetString(_resourceID);

        var modelClientValidationEqualToRule = new ModelClientValidationEqualToRule(strMsg, _OtherPropertyName);

        yield return modelClientValidationEqualToRule;
    }

在jQuery中

  $.validator.addMethod("equalto",
   function (value, element, parameters) {
       return value;

   });

    $.validator.unobtrusive.adapters.add('equalto', [], function (options) {

        options.rules.equalto = {};
        options.messages['equalto'] = options.message;
    });

但是,现在我正在使用.Net Core 1.0,其中此接口已完全更改,并且它没有'ModelClientValidationEqualToRule'类可用。

在阅读了documentation后,我发现验证将在数据属性的帮助下完成。所以,我已经实现了所需的字段属性,范围字段属性,电子邮件地址属性等。

但是,我不知道如何验证密码和确认密码?

对此有任何帮助表示赞赏!

jquery asp.net-core asp.net-core-mvc asp.net-core-1.0
1个回答
5
投票

IClientModelValidator只有一种方法可以实现,这里显示的示例来自一个自定义的EnforceTrueValidator,如果有必要的注册协议,我会用它有条件地强制检查注册页面上的复选框。此方法添加所需的数据属性以连接客户端不显眼的验证。

    public void AddValidation(ClientModelValidationContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        CheckForLocalizer(context);
        var errorMessage = GetErrorMessage(context.ModelMetadata.GetDisplayName());
        MergeAttribute(context.Attributes, "data-val", "true");
        MergeAttribute(context.Attributes, "data-val-enforcetrue", errorMessage);
        MergeAttribute(context.Attributes, "data-val-other", "#" + OtherProperty);
    }

你可以看到完整的类here,并且必须添加到自定义客户端验证页面的自定义js是here

在我的情况下,“其他”属性只是一个布尔我用来确定是否应该应用此验证器,因为我在多租户场景中使用它并且并非所有租户都可以强制执行注册协议,如果租户我将布尔值设置为true已经填写了注册协议

© www.soinside.com 2019 - 2024. All rights reserved.