Léo Coco
Léo Coco

Reputation: 4282

Vue.js - Element UI - Dynamic rules validation form

I'm using vue-js2.3 and element-ui.

I would like to define the validation rules of my form dynamically

Example

https://jsfiddle.net/cgL6y9kq/

Problem

The required is not dynamically defined by phoneMandatory

Questions

How can I change the attribute on an existing rule dynamically? How can I add or remove rules dynamically ?

Upvotes: 7

Views: 10874

Answers (1)

thanksd
thanksd

Reputation: 55664

You have your rules property in the component's data method. This means it will not updated based on changes to other data properties.

You should use a computed property for rules instead:

computed: {
  rules() {
    return { 
      phone: [{ 
        required: this.phoneMandatory, 
        message: 'Please input phone', 
        trigger: 'blur' 
      }]
    }
  }
},

Now, when this.phoneMandatory updates, so will the component's rules property.

Here's a working fiddle.

Upvotes: 20

Related Questions