当其他字段更改时,验证1字段(不显眼),并仅检查1个规则

And*_*ker 4 jquery unobtrusive-validation asp.net-mvc-4

当另一个字段中的值发生变化时,有没有办法在一个字段上触发特定的 jquery-unobtrusive规则?

我有一个带有两个日期字段的表单(比如开始/结束),验证end必须大于start.在已经设置的更改end后的简单情况下,这可以正常工作start.不做的是允许是:

  • 设置end第一,然后设置start
  • start在两者都已设置之后进行更改,并违反约束

服务器端验证当然会捕获它,但end即使在修复后仍然设置错误仍然很糟糕start,或者当值in end更改为无效值时没有出现错误.触发特定规则的原因是我不希望在用户有机会输入值之前触发相同字段上的规则requireddate格式化规则.表格开始"干净".但是,如果这是不可能的,那么解雇所有规则是可以的.

很抱歉没有代码示例,但我甚至不知道从哪里开始.

更新:

我目前所做的是在模型中挖掘(因为这是一个asp.net mvc项目),找到属性,并直接读取它的属性.

var controllerCtx = ViewContext.Controller.ControllerContext;
var da = ViewData.ModelMetadata.GetValidators(controllerCtx)
            .SelectMany(x => x.GetClientValidationRules())
            .Where(x => x.ValidationType == "isdateafter")
            .FirstOrDefault();

var otherid = da == null ? "" : da.ValidationParameters["propertytested"];
Run Code Online (Sandbox Code Playgroud)

然后在普通的HTML部分中,我start对它进行测试并查看它是否是日期选择器,然后连接基本检查,并启动所有验证规则.由于规则不多,我只是end在运行之前检查字段中是否有值.我想使用下面的巧妙解决方案,并在本周有一点空闲时间时给它一个机会.

@if (otherid != "") {
    <text>
    var other = $("#@otherid");
    if (other && other.hasClass('hasDatepicker')) { // if the other box is a date/time picker
       other.datetimepicker('option', 'onSelect', function(dateText, instance) {
           var lowerTime = $(this).datetimepicker('getDate');
           $("#@id").datetimepicker('option', 'minDate', new Date(lowerTime.getTime()));
           if ($("#@id").val()) { // if there is a value in the other
                $('form').data('validator').element('#@id');
           }
        });
    }
    </text>
}
Run Code Online (Sandbox Code Playgroud)

jcr*_*898 9

这可能对你有用......

$('form').data('validator').element('#Key')
Run Code Online (Sandbox Code Playgroud)

这会从您的表单中获取验证程序,并强制对单个项目进行验证.

http://docs.jquery.com/Plugins/Validation/Validator/element#element

UPDATE

看看这是否继续有用!

$.extend($.validator.prototype, {
        elementWithRule: function(element, rule) {
            element = this.clean(element);
            this.lastElement = element;
            this.prepareElement(element);
            this.currentElements = $(element);
            var result = this.checkSpecificRule(element, rule);
            if (result) {
                delete this.invalid[element.name];
            } else {
                this.invalid[element.name] = true;
            }
            if (!this.numberOfInvalids()) {
                // Hide error containers on last error
                this.toHide = this.toHide.add(this.containers);
            }
            this.showErrors();
            return result;
        },
        checkSpecificRule: function(element, rule) {
            element = this.clean(element);

            // if radio/checkbox, validate first element in group instead
            if (this.checkable(element)) {
                element = this.findByName(element.name).not(this.settings.ignore)[0];
            }

            var findRule = { },
                checkRule = $(element).rules()[ rule ];
            var rules;

            if (checkRule) {
                findRule[rule] = checkRule;
                rules = findRule;
            }

            if (!rules) {
                return;                
            }
            var dependencyMismatch = false;
            for (var method in rules) {
                var rule = { method: method, parameters: rules[method] };
                try {
                    var result = $.validator.methods[method].call(this, element.value.replace( /\r/g , ""), element, rule.parameters);

                    // if a method indicates that the field is optional and therefore valid,
                    // don't mark it as valid when there are no other rules
                    if (result == "dependency-mismatch") {
                        dependencyMismatch = true;
                        continue;
                    }
                    dependencyMismatch = false;

                    if (result == "pending") {
                        this.toHide = this.toHide.not(this.errorsFor(element));
                        return;
                    }

                    if (!result) {
                        this.formatAndAdd(element, rule);
                        return false;
                    }
                } catch(e) {
                    this.settings.debug && window.console && console.log("exception occured when checking element " + element.id
                        + ", check the '" + rule.method + "' method", e);
                    throw e;
                }
            }
            if (dependencyMismatch)
                return;
            if (this.objectLength(rules))
                this.successList.push(element);
            return true;
        }
    });

// Then use it like this...
$('form').data('validator').elementWithRule('#Key', 'required');
Run Code Online (Sandbox Code Playgroud)

似乎没有任何内置方法可以做到这一点,所以我只是一起攻击了一些东西!:)