使用 IClientModelValidator 进行验证

Validation using IClientModelValidator

在以前的版本 (RC1) 中,我使用接口 IClientModelValidator 来 validate/compare 密码和使用 'ModelClientValidationEqualToRule' class 确认密码,如下所示

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”class。

阅读 documentation 后,我了解到验证将在数据属性的帮助下完成。所以,到目前为止,我已经实现了必填字段属性、范围字段属性、电子邮件地址属性等

但是,我不清楚如何验证密码和确认密码?

感谢任何帮助!

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);
    }

你可以看到完整的classhere, and the custom js that must also be added to the page for the custom client side validation is here

在我的例子中,"other" 属性 只是一个布尔值,我用它来确定是否应该应用这个验证器,因为我在多租户场景中使用它,并不是所有租户都可以强制注册协议,如果租户已填写注册协议,我将布尔值设置为 true