在字段有效之前,如何禁用聚合物中的按钮?

How can I disable a button in polymer until a field is valid?

我喜欢用聚合物创建一个基本的对话。用户应输入类别名称,如果他输入了某些内容,他可以按下按钮 save/send。只要类别字段中没有值或只要类别字段中存在验证错误,就应该禁用该按钮。

我试过了,但最初并没有将按钮设置为禁用。

<paper-input required auto-validate invalid="{{invalid}}"></paper-input>
<paper-button disabled$="[[invalid]]">Send</paper-button>

Polymer({
    is: 'list',
    properties: {  
        invalid: {
            type: Boolean
        },
        ...

如果我在输入上使用函数 validate() 来计算按钮值,它也会触发输入的无效状态(错误消息),尽管用户可能尚未输入内容。

我该如何解决这个问题?

参考:paper-inputpaper-button

proposal with iron-form:

<form is="iron-form" method="get" action="/" id="eventsDemo">
  <paper-input name="name" label="Name" required auto-validate></paper-input>
  <paper-button raised disabled id="eventsDemoSubmit">
</form>

<script>
  eventsDemo.addEventListener('change', function(event) {
    // Validate the entire form to see if we should enable the `Submit` button.
    eventsDemoSubmit.disabled = !eventsDemo.validate();
  });
  document.getElementById('eventsDemo').addEventListener('iron-form-submit', function(event) {
    eventsDemoSubmit.disabled = false;
  });
  ...

这是一种可能的解决方案:Plunk

<paper-input  
                label="Insert number from the range [1, 10]"
                id="step"
                type="number" 
                min="1" 
                max="10"
                value="{{value}}"
                editable

                required

                auto-validate="true"
                invalid="{{invalid}}"
                preventInvalidInput
                error-message="value: {{value}}  - means invalid is {{invalid}}"

                on-change="stepChange">

</paper-input>


        <br>
        value: {{value}}
        <br>
        invalid: {{invalid}}
        <br><br><br>
        <paper-button raised disabled$="{{invalid}}">Enable on valid input</paper-button>

您可以使用将 invalidvalue 作为参数的计算绑定。

<paper-button disabled$="[[isDisabled(invalid, value)]]">Enable on valid input</paper-button>

isDisabled 函数随后会检查该值是否已设置。例如像这样:

isDisabled: function(invalid, value) {
    return invalid || value.length === 0;
}

我不确定我是否完全满足您的要求。当然,您可以尝试 computed bindings and computed properties。 你有一个很好的 cheat-sheet 这里 https://meowni.ca/posts/polymer-cheatsheet/