【问题标题】:knockout validation after input输入后敲除验证
【发布时间】:2018-04-11 18:26:11
【问题描述】:

我有一堂课:

Model.Feedback.Data = function () {
    var self = this;

    self.Name = ko.observable('').extend({
        pattern: {
            params: /^[A-Za-z]+[A-Za-z\s]*$/,
            message: 'Invalid name'
        }
    });

    self.Email = ko.observable('').extend({     
        pattern: {
            params: /^[a-zA-Z0-9!#$%&'*+/=?^`{|}~]+(?:[\._-][a-zA-Z0-9!#$%&'*+/=?^`{|}~]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/,
            message: 'Invalid e-mail'
        },
        maxLength: {
            params: 256,
            message: 'Long email'
        }
    });

    return this;
};

我有一个 HTML 代码:

<form class="form-additem-checkin" data-bind="submit: send">
    <!--ko with: Data-->
    <div class="form-additem-group-row">
        <div class="form-additem-group-row__col form-additem-group-row__col_label"><div class="form-additem-group__label">E-mail</div></div>
        <div class="form-additem-group-row__col form-additem-group-row__col_field">
            <input type="text" class="field field_type2 input--full" placeholder="You e-mail" data-bind="textInput: Email" />
            <div class="form-additem-group-row__error" data-bind="validationMessage: Email"></div>
        </div>
    </div>  
    <div class="form-additem-group-row">
        <div class="form-additem-group-row__col form-additem-group-row__col_label"><div class="form-additem-group__label">Name</div></div>
        <div class="form-additem-group-row__col form-additem-group-row__col_field">
            <input type="text" class="field field_type2 input--full" placeholder="You name" data-bind="textInput: Name" />
            <div class="form-additem-group-row__error" data-bind="validationMessage: Name"></div>
        </div>
    </div>
    <!--/ko-->
    <div class="form-additem-auth__button">
        <button type="submit" class="btn btn--green form-additem-button">Send</button>
    </div>
</form>

现在,如果您在电子邮件字段中输入 test@a,您将立即收到一条错误消息。

字段失去焦点后如何检查字段?

【问题讨论】:

  • 如果您将数据绑定从“textInput”更改为“value”,它只会在焦点更改时触发更新。

标签: validation knockout.js knockout-validation


【解决方案1】:

使用value 绑定而不是textInput 似乎可以解决它。 (学分:杰森·斯派克)

或者,您可以使用hasFocus 绑定并在没有焦点时显示错误消息。 (不那么优雅+一旦输入再次聚焦,消息就会消失。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-20
    • 2014-06-04
    • 2014-10-19
    • 2012-11-23
    • 2013-01-13
    • 2015-08-19
    • 2013-01-21
    • 2012-05-22
    相关资源
    最近更新 更多