0

I have a project where I need to do form validation. If the fields are not correctly entered the formErrors object will get a string variable with the correct error text. So in the case of email the error String will be put in formErrors.email. This String can be printed out in the p element that shows the error even the visibility of this p element can be shown or hidden depending on the state of formErrors.email like v-if="formErrors.email".

But when I try to give the input element a red border color using :class="{formErrors.email : text-red-primary}" the linter throws an error Parsing error: Unexpected token .. But how do i enable this class binding with a variable inside the formErrors object.

<input
          type="text"
          name="email"
          id="email"
          v-model="email"
          placeholder="Email address"
          class="w-full px-4 py-3 border rounded-lg text-black-primary focus:outline-none text-sm"
          :class="{formErrors.email : text-red-primary}"
        />
        <p v-if="formErrors.email" class="text-red-primary text-xs mt-1 ml-1">{{formErrors.email}}</p>
      </div>

2 Answers 2

1

Your class binding is currently backwards: the key should be the class name, and the value should be truthy/falsy (e.g., a non-empty string would be truthy). Also, the key (text-red-primary) needs to be quoted because it contains non-alphanumeric characters (-):

<!-- ❌ -->
<input :class="{ formErrors.email : text-red-primary }">

<!-- ✅ -->
<input :class="{ 'text-red-primary' : formErrors.email }">
Sign up to request clarification or add additional context in comments.

Comments

0

You can create computed property say isEmailInValid which return true/false

and use it in template like this

:class="{'text-red-primary': isEmailInValid}"

dynamic class gets applied when condition is true only.

You can checkout vue docs for more info https://v2.vuejs.org/v2/guide/class-and-style.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.