0

我有一个包含最大值和最小值的对象,所以我希望在所有编辑和创建视图中显示客户端验证消息,以防用户插入的最小值大于最小值。BR

4

1 回答 1

1

您可能需要客户端和服务器端验证。实现自己的验证可能会很好。我做了类似的事情,我想确保一个字段与另一个字段的值不同。不过我不是从头开始的。我使用了来自 Microsoft 的 Simon J Ince 的一些代码。他在他的博客上有。基本上,他有条件验证的基础(您可以根据另一个字段的值进行验证)。我从他的 ConditionalAttributeBase 继承并实现了 IClientValidatable 接口(这是您向浏览器发送 java 脚本将检查的依赖字段的方式。)

/// <summary>
/// A validator for ensuring that the value of this field does NOT equal the value of another field.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public class NotEqual:ConditionalAttributeBase, IClientValidatable
{
    public string DependentProperty { get; set; }

    /// <summary>
    /// Returns client validation rules for NotEqual
    /// </summary>
    /// <param name="metadata">The model metadata.</param>
    /// <param name="context">The controller context.</param>
    /// <returns>
    /// The client validation rules for NotEqual.
    /// </returns>
    IEnumerable<ModelClientValidationRule> IClientValidatable.GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
                       {
                           ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
                           ValidationType = "notequal",
                       };
        string depProp = BuildDependentPropertyId(metadata, context as ViewContext);
        rule.ValidationParameters.Add("dependentproperty", depProp);

        yield return rule;
    }

    /// <summary>
    /// Builds the dependent property id.
    /// </summary>
    /// <param name="metadata">The metadata.</param>
    /// <param name="viewContext">The view context.</param>
    /// <returns></returns>
    protected string BuildDependentPropertyId(ModelMetadata metadata, ViewContext viewContext)
    {
        return QualifyFieldId(metadata, DependentProperty, viewContext);
    }

    /// <summary>
    /// Validates that the value does not equal the value of the dependent value if the dependent value is not null
    /// </summary>
    /// <param name="value">The value to validate.</param>
    /// <param name="validationContext">The context information about the validation operation.</param>
    /// <returns>
    /// An instance of the <see cref="T:System.ComponentModel.DataAnnotations.ValidationResult"/> class.
    /// </returns>
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        // check if the current value matches the target value
        if (value != null && GetDependentFieldValue(DependentProperty, validationContext).ToString() == value.ToString())
        {

                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }

        return ValidationResult.Success;
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="NotEqual"/> class.
    /// </summary>
    /// <param name="dependentProperty">The dependent property.</param>
    public NotEqual(string dependentProperty)
    {
        DependentProperty = dependentProperty;
    }

}$

接下来我调整了javascript:

    (function ($) {
        $.validator.addMethod('notequal',
            function (value, element, parameters) {
                var id = '#' + parameters['dependentproperty'];
                var depControl = $(id);
                var control = $(element);
                if (control.val() === depControl.val())
                    return "";
                return true;
            }
        );

    $.validator.unobtrusive.adapters.add(
        'notequal',
        ['dependentproperty'],
        function (options) {
            options.rules['notequal'] = {
                dependentproperty: options.params['dependentproperty']
            };
            options.messages['notequal'] = options.message;
        }
    );

        $.validator.addMethod('notequaltwo',
        function (value, element, parameters) {
            var id = '#' + parameters['dependentproperty'];
            var depControl = $(id);
            var control = $(element);
            if (control.val() === depControl.val())
                return "";
            return true;
        }
    );

        $.validator.unobtrusive.adapters.add(
        'notequaltwo',
        ['dependentproperty'],
        function (options) {
            options.rules['notequaltwo'] = {
                dependentproperty: options.params['dependentproperty']
            };
            options.messages['notequaltwo'] = options.message;
        }
    );
})(jQuery);$

希望你能看到如何调整我的代码来做你想做的事,基本上你必须转换类型(如果类型不转换,不要做任何事情,你应该选择其他验证器它。)然后进行比较。

于 2012-05-08T14:18:45.413 回答