【问题标题】:what is the best way to implement a client side validation to check that the Max value is greater than the Min value inside my asp.net MVC实现客户端验证以检查最大值是否大于我的 asp.net MVC 中的最小值的最佳方法是什么
【发布时间】:2012-05-02 20:36:10
【问题描述】:

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

【问题讨论】:

  • 你的意思是范围验证吗?
  • 感谢您的回复,不,我不是说范围。我想做的是我有一个名为 LabResult 的对象,其中每个 LabResult 对象都有两个医生应该输入的属性; Test_Min_Value 和 Test_Max_Value。所以为了避免不合逻辑的数字,我想检查输入的 Test_Max_Value 是否应该大于 Test_Min_Value。 BR

标签: asp.net asp.net-mvc-3 data-annotations


【解决方案1】:

您可能需要客户端和服务器端验证。实现自己的验证可能会很好。我做了类似的事情,我想确保一个字段与另一个字段的值不同。不过我不是从头开始的。我使用了来自 Microsoft 的 Simon J Ince 的一些代码。他的博客上有here。基本上,他有条件验证的基础(您可以根据另一个字段的值进行验证)。我从他的 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);$

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    • 2017-07-09
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    相关资源
    最近更新 更多