VueJS中的条件验证

时间:2015-09-17 23:20:20

标签: javascript vue.js

我正在使用带有vue-validator的VueJS,我一直在努力进行简单的条件验证。文档中提供的示例似乎不起作用,至少在我的情况下不行。

我想要完成的是要求两个输入组(observer_firstNameobserver_lastName)如果条件(showObserverEntry)是true并且需要另一个({{1}如果是role

因此,如果falseshowObserverEntry,则false应该是必需的/可见的。如果roleshowObserverEntry,则true不应被要求或不可见,roleobserver_firstName应该是必需且可见的。

加载页面并observer_lastName设置为showObserverEntry后,一切正常,当切换到false时,它会继续有效,但当它再次返回true时验证停止为false工作。在数据输出处查看时,验证数据会更改为最初有数据的role

删除了其他方法的Vue实例:

validation { }

表单字段:

var vm = new Vue({
    el: "#scheduleContainer",
    validator: {
        validates: {
            requiredIf: function (val, condition){
                return val && condition
            }
        }
    },
    data: {
        loading: true,
        stationId: stationId,
        date: initialDate,
        dateFormatted: initialDateFormatted,
        nextDate: null,
        prevDate: null,
        entries: [],
        requestEntries: [],
        roles: [],
        roleStaff: [],
        showObserverEntry: false,
        startPickerDatetime: null,
        endPickerDatetime: null,
        shiftEntry: {
            start: null,
            end: null,
            role: null,
            member: "",
            observer: {
                firstName: "",
                lastName: ""
            }
        }
    },
    computed: {
        validField: function () {
            return this.validation.shiftEntry.observer.firstName.valid &&
                this.validation.shiftEntry.observer.lastName.valid
        }
    },
    methods: {
        getRoleStaff: function () {
            if (this.shiftEntry.role != '' && this.shiftEntry.role != 'observer') {
                this.$http.post('/members/schedule/manage/json/roles/staff', {id: this.shiftEntry.role})
                    .success(function (data) {
                        this.$set('roleStaff', data.members);
                        vm.shiftEntry.member = "";
                        vm.showObserverEntry = false;
                        vm.shiftEntry.observer.firstName = "";
                        vm.shiftEntry.observer.lastName = "";
                    });
            } else if (this.shiftEntry.role == 'observer') {
                this.showObserverEntry = true;
                this.resetFields()
            }
            else {
                this.showObserverEntry = false;
                this.roleStaff = [];
            }
        },
        resetFields: function () {
            this.roleStaff = [];
            this.shiftEntry.role = "";
            this.shiftEntry.member = "";
            this.shiftEntry.observer.firstName = "";
            this.shiftEntry.observer.lastName = "";
        },
        conditionalField: function (response, type) {
            return response === type
        }
    }
});

1 个答案:

答案 0 :(得分:1)

这是因为Vue.js中的一个错误。原因:如果我们根据特定条件(v-if)删除一个或多个v模型,那么它将使所有其他验证停用。

请参阅问题:https://github.com/vuejs/vue-validator/issues/69