Home > OS >  Highlight specific Input Red/Invalid based on API response
Highlight specific Input Red/Invalid based on API response

Time:05-21

Based on the API reponse

enter image description here

I caught it and display a red alert, but on top of that, I would like to also trigger red highlight to the name input.

enter image description here

my input

<v-text-field
    :
    dense
    outlined
    v-model="name"
    :rules="form.rules.name"
    label="Name"
    required
></v-text-field>

css

>>> .invalid .v-label {
    color: #b13737 !important;
    caret-color: #ff5252 !important;
}

>>> .invalid input {
    color: #b13737 !important;
    caret-color: #ff5252 !important;
}

>>> .invalid .v-text-field--outlined fieldset {
    border: 2px solid #b13737 !important;
}

catch it

this.invalidName = true //turned it to true when error detected 
this.alert = true
this.alertColor = 'red'
this.alertMessage = response.data.error.detail

result

I can only turn label and the color of the text red

enter image description here

CodePudding user response:

Override vuetify's css can be a little tricky sometimes. Try doing it like this:

.theme--light.v-text-field--outlined:not(.v-input--is-focused):not(.v-input--has-state)
  > .v-input__control
  > .v-input__slot
  fieldset {
  border: 2px solid #b13737 !important
}

Preview

CodePudding user response:

Don't mess with the Vuetify input error state CSS manually. Instead try to make use of the error (boolean) and error-messages (string or array) ((if you are not hiding details)) props of the text-field.

If you can parse the error in the response, I would recommend constructing an inputErrors object, where the keys are the names of the fields and values are (possibly) the error message(s). Especially if you would show multiple error fields in one submission.

You could parse data.error.reference with .split(':') and use index [0] as the key of the above inputErrors object and index [1] as the value.

Then you can use the error props of the text-field programatically.

<v-text-field
  :error="inputErrors['name']"
  :error-messages="inputErrors['name']"
>

It's possible you don't need both. It might be the case if error-messages is not null the error state is true.

  • Related