添加带引用字段的Parsley.js验证器

时间:2014-04-03 12:47:23

标签: javascript validation parsley.js

我想为我的表单添加一些检查,其状态与其他字段有关。值(即我有一个范围形式,from字段必须小于to字段,反之亦然。我在目前的Validators上找不到类似的东西,所以我试着自己添加。

所以,我将这两个函数添加到Assert.prototype

GreaterThanReference: function ( reference ) {
    this.__class__ = 'GreaterThanReference';
    if ( 'undefined' === typeof reference )
        throw new Error( 'GreaterThanReference must be instanciated with a value or a function' );
    this.reference = reference;
    this.validate = function ( value ) {
        var reference = 'function' === typeof this.reference ? this.reference( value ) : this.reference;
        if ( '' === value || isNaN( Number( value ) ) )
            throw new Violation( this, value, { value: Validator.errorCode.must_be_a_number } );
        if ( this.reference.value >= value )
            throw new Violation( this, value );
        return true;
    };
    return this;
}

LessThanReference: function ( reference ) {
    this.__class__ = 'LessThanReference';
    if ( 'undefined' === typeof reference )
        throw new Error( 'LessThanReference must be instanciated with a value or a function' );
    this.reference = reference;
    this.validate = function ( value ) {
        var reference = 'function' === typeof this.reference ? this.reference( value ) : this.reference;
        if ( '' === value || isNaN( Number( value ) ) )
            throw new Violation( this, value, { value: Validator.errorCode.must_be_a_number } );
        if ( this.reference.value <= value )
            throw new Violation( this, value );
        return true;
    };
    return this;
}

以及其他两个ParsleyValidator.prototype.validators

greaterthan: function (value) {
    return $.extend(new Validator.Assert().GreaterThanReference(value), {
        priority: 256,
        requirementsTransformer: function () {
        return { name : $(value).attr('alt'), value : +$(value).val() };
    }});
}

lessthan: function (value) {
    return $.extend(new Validator.Assert().LessThanReference(value), {
        priority: 256,
        requirementsTransformer: function () {
        return { name : $(value).attr('alt'), value : +$(value).val() };
    }});
}

然后我想在引用字段上添加启示检查,这样如果我只更改引用字段的值,我仍然可以验证表单(在范围示例中,如果我从值更改,我应该验证到字段。如果我改为值,我应该从字段验证)。为此,我编辑了ParsleyField.prototype.addConstraint

addConstraint: function (name, requirements, priority, isDomConstraint, isReference) {
    name = name.toLowerCase();
    if ('function' === typeof window.ParsleyValidator.validators[name]) {
        var constraint = new ConstraintFactory(this, name, requirements, priority, isDomConstraint);
        // if constraint is a referenced one, I add the specular constraint on the referenced field
        if((name == 'lessthan' || name == 'greaterthan') && isReference !== true) {
            // I check if I already instanciated the referenced ParsleyField
            var referencedField = $(requirements).data('Parsley') && $(requirements).data('Parsley').__class__ == 'ParsleyField' ?
                $(requirements).data('Parsley') :
                new ParsleyField($(requirements), this.parsleyInstance).init();
            referencedField.addConstraint(name == 'lessthan' ? 'greaterthan' : 'lessthan', '#' + this.$element.attr('id'), priority, isDomConstraint, true);
        }
        // if constraint already exist, delete it and push new version
        if ('undefined' !== this.constraintsByName[constraint.name])
            this.removeConstraint(constraint.name);
        this.constraints.push(constraint);
        this.constraintsByName[constraint.name] = constraint;
    }
    return this;
}

详细地说,我添加了isReference参数来知道我是否已经在引用字段上添加了反向约束,以避免循环引用。然后,以一种非常可怕的方式,我检查我添加的约束是否有引用并且不是已经引用的约束(也许可以通过添加某种&#34;约束类型来改进#&# 34;对于检查其他字段的约束,可以间接(或引用),并指向那些只检查值的人。如果这个条件为真,我必须将新约束添加到已经实例化的ParsleyField,或者如果尚未实例化,则添加到新的ParsleyField

此方法存在问题。如果我在引用尚未实例化的字段的字段上添加约束,当Parsley的正常流程到达该字段时,它会覆盖它,从而消除我之前添加的约束。

零问题:这是实现我想要的正确方法吗?我承认我没有太多探索Parsley API,但我想尽可能少地使用功能,因为我使用相同的检查服务器端,我应该能够做同样的事情双方的事情。

如果零答案是“是”,我该如何解决覆盖问题?可能我应该能够在ParsleyField实例化检查它是否已经实例化,但是如何实现?

1 个答案:

答案 0 :(得分:1)

我不知道你正在使用哪种版本的欧芹js,也许我的回答现在不实际。但是,我在v.2.0.2中遇到了同样的问题。幸运的是,docs包含编写自定义验证器的教程。 您可以查看以下https://github.com/mvpotter/parsley-extra-validators。如果我理解正确,他们会完全按照你的需要做。任何反馈都表示赞赏。