Friday, 26 October, 2018 UTC


Summary

Let’s explore how to extend Vuetify’s input field validation to replace empty fields with default values.
Say we have a form with some fetched values, for example, a user profile form. The user wants to edit his data and then removes his login and moves to another field instead of actually creating a new login. The login field
is empty now. Things look fine with the default Vuetify validation for empty fields:
Vue’s two-way binding is syncing our data with the input and we now have a blank login field and we don’t want that behavior here. Instead we want to fill them with the initial values we fetched.
Getting Started
Let’s add a simple function to solve our problem. In real projects you’ll probably make use of a store, but here I’ll use a simple data object to save the values.
We can take an example from the Vuetify website and add the user object:
<v-form> <v-text-field v-model='gator.login' label='Login' :rules='loginRules' required ></v-text-field> <v-text-field v-model='gator.email' :rules='emailRules' label='E-mail' required ></v-text-field> </v-form> 
export default { data() { return { loginRules: [v => !!v || "The input is required"], emailRules: [ v => !!v || "E-mail is required", v => /[email protected]+/.test(v) || "E-mail must be valid" ], gator: { login: "", email: "" } }; }, mounted() { this.gator.login = "crocodilian"; this.gator.email = "[email protected]"; } }; 
At first, create an object to save the fetched data and fill it:
export default { data() { return { currentGator: { login: null, email: null } }; }, mounted() { this.currentGator.login = this.gator.login; this.currentGator.email = this.gator.email; } }; 
Let’s listen to the change event and check if some of the values are empty. As we have two fields, pass-in the field name as the second argument:
<v-text-field v-model='gator.login' label='Login' :rules='loginRules' @change='checkEmpty($event, "login")' required ></v-text-field> <v-text-field v-model='gator.email' :rules='emailRules' @change='checkEmpty($event, "email")' label='E-mail' required ></v-text-field> 
And write the simple checkEmpty method:
methods:{ checkEmpty(value, field){ if(!value.trim()){ this.user[field] = this.currentGator[field]; } } } 
That’s it! Now important fields are never empty. And if you need to add one more field just call the method with the change event and pass-in the field name.
Adding a New Input
For example, this is how you could add a name to the gator and the currentGator objects:
<v-text-field v-model='gator.name' label='Name' :rules='loginRules' @change='checkEmpty($event, "name")' required ></v-text-field> 
export default { data() { return { gator: { login: "", email: "", name: "" }, currentGator: { login: null, name: null, email: null } }; }, mounted() { this.gator.name = "Cayman"; this.currentGator.name = this.gator.name; } };