Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js - Element UI - Dynamic rules validation form

Tags:

vuejs2

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 ?

like image 848
Léo Coco Avatar asked Jun 06 '17 19:06

Léo Coco


1 Answers

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.

like image 113
thanksd Avatar answered Jan 03 '23 19:01

thanksd