7

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 ?

Léo Coco
  • 4,022
  • 11
  • 52
  • 97

1 Answers1

20

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.

thanksd
  • 54,176
  • 22
  • 157
  • 150