7

Knockout 検証プラグインには、エラー クラスをエラーのある入力の親または親の親に適用するオプションがありますか? そうでない場合、これを行うためにノックアウト検証を変更するアプローチを提案できる人はいますか?

私が達成しようとしていることの例については、次のフィドルを参照してください。すぐに使えるノックアウト検証は入力のクラスを設定しますが、代わりにそれを含むコントロールグループのクラスを設定したいと思います:

http://jsfiddle.net/fbA4m/1/

意見

<p>Clear the field and tab out of it to "see" the current behaviour - error class is added directly to the input by knockout validation. But I want to add class "error" to control-group containing the input instead of directly to the input.</p>
<div class="form-horizontal">
<div class="control-group">
<label class="control-label">Field</label>
<div class="controls">
<input type="text" data-bind="value: testField" class="">
</div>
</div>
    <button data-bind="click: setErrorOnControlGroup">Click to see desired effect</button>
</div>

Javascript

ko.validation.configure({
    registerExtenders: true,
    messagesOnModified: true,
    decorateElement: true,
    errorClass: 'error',
    insertMessages: false,
    parseInputAttributes: true,
    messageTemplate: null
});

var viewModel = {
    testField: ko.observable("123").extend({required: true}),
    setErrorOnControlGroup: function() {
        $("input.error").removeClass("error");
        $(".control-group").addClass("error");
    }
};

ko.applyBindings(viewModel);

スタイルシート(説明のみ - Twitter のブートストラップ スタイルを使用したいので、これは必要ありません)

/*NOTE: This is not actually the style I want, it just illustrates the default behaviour of knockout validation*/
input.error {
    background-color: #aaffaa;
}

Twitter のブートストラップ スタイルを使用しており、入力の親コントロール グループ要素を使用して「エラー」入力のスタイルを設定しているためです。

4

2 に答える 2

3

効果を得るためにミューテックスのフィドルを微調整しました。 http://jsfiddle.net/3vGVC/9/ . ただし、おそらく、適用する css クラスを指定できるように、改善の余地があります。これは、コンテナに適用できる bindingHandler です。

ko.bindingHandlers.validationElement = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
    var valueIsValid = valueAccessor().isValid();
    if(!valueIsValid) {
        $(element).addClass("error");
    }
    else {
        $(element).removeClass("error");
    }
}

}

于 2013-04-29T21:57:56.110 に答える