Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

javascript - How to add custom validator to paper-input?

Need to add a custom validator which does some complex validation based on the values of other fields in the html.

Tried adding custom validator function as an attribute to the paper-input element but it wont get called at all.

    <dom-module id='custom-ele'>
            <paper-input is="iron-input" id='input_1' label='Label_1' validator='validate_1'></paper-input>
            <paper-input is="iron-input" id='input_2' label='Label_2' validator='validate_2'></paper-input>
            ...
    </dom-module>
    <script>
    Polymer({

        is: 'custom-ele',

        validate_1: function() {
            //validation code
        },

        validate_2: function() {
           //validation code 
        }

    });
    </script>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The validator has to implement IronValidatorBehavior (see docs). Also, if you want to validate automatically, you need to set the auto-validate attribute. To achieve your goal you could create a custom validator for each type of validation that you want to use. Alternatively, you could create a generic custom validator and set the validate function upon initialisation. Here's an example.

Polymer({

    is: 'custom-validator',

    behaviors: [
        Polymer.IronValidatorBehavior
    ]
});

<dom-module id='validation-element'>
    <template>
        <custom-validator id="valid1" validator-name="validator1"></custom-validator>
        <custom-validator id="valid2" validator-name="validator2"></custom-validator>
        <paper-input auto-validate id='input_1' label='Label_1' validator='validator1'></paper-input>
        <paper-input auto-validate id='input_2' label='Label_2' validator='validator2'></paper-input>
    </template>
</dom-module>
<script>

    Polymer({

        is: 'validation-element',

        validate1: function(value) {
            //validation code
            console.log("validate1");
            return value.length > 3;
        },

        validate2: function(value) {
            //validation code
            console.log("validate2");
            return value.length > 5;
        },

        ready: function() {
            this.$.valid1.validate = this.validate1.bind(this);
            this.$.valid2.validate = this.validate2.bind(this);
        }

    });

</script>

You can find a working example in this plunk.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...