Gazz
Gazz

Reputation: 1075

Remove validation error upon change on the input field

I'm new to using Vue and wondering how I can get a validation error removed from its associated input field as the input field value changes. I store my input field values in an object called fields inside data() as below (small snippet):

 fields: {
  email_type: '',
  date_of_birth: '',
  country_of_birth: '',
}

I also store my validation errors inside an object called errors.

When the user submits the form and gets validation errors, the error object fills up. An example is below:

{"email_type":["The email type field is required."],
"date_of_birth":["The date of birth field is required."],
"country_of_birth":["The country of birth field is required."]

To display the validation error under the input, I do:

<small class="font-weight-bold help text-danger" v-if="errors.{{$name}}" v-text="errors.{{$name}}[0]"></small>

A sample of my inputs are (I use Laravel blade to insert the "name" of the field) with {{$name}}:

<input @change="removeValidationError(errors.{{$name}})" v-model="fields.{{$name}}" class="form-control" value="">

The removeValidationError() method is what should be removing that specific validation error from the errors object however this is not working. My removeValidationError method is below:

removeValidationError : function(errorField){

    if(errorField !== undefined){
        console.log(errorField);
        errorField = "";
        delete errorField;
    }

},

As you can see I have tried both to empty the field as well as delete it but this has no effect. I do not even get any error messages in the console however when I console.log errorField it does display the error message.

(Additional info, I get my validation using Laravel)

What is the best approach for this? Thanks

Upvotes: 0

Views: 3317

Answers (1)

Ashvin777
Ashvin777

Reputation: 1482

There is an issue with your data binding done in the template, the values of an Objectcan't be evaluated using errors.{{$name}} in the template. It won't compile and ideally should throw an error. The correct solution is to access properties using angle brackets - errors[$index]

Instead of

<small class="font-weight-bold help text-danger" v-if="errors.{{$name}}" v-text="errors.{{$name}}[0]"></small>

<input @change="removeValidationError(errors.{{$name}})" v-model="fields.{{$name}}" class="form-control" value="">

It should be

<small class="font-weight-bold help text-danger" v-if="errors[$name]" v-text="errors[$name][0]"></small>

<input @change="removeValidationError(errors[$name])" v-model="fields[$name]" class="form-control" value="">

Upvotes: 1

Related Questions