We can highlight the border color of an invalid input field, like a password in Vue.js. We can keep a reactive state which will observe whether or not the password is valid. If it finds that the password is invalid, it’ll add a CSS class to the element.
Here’s how we can do that:
<script setup>
import { ref } from 'vue';
const isInputInvalid = ref(false);
const inputPasswordValue = ref('');
const checkInputValidity = () => {
isInputInvalid.value = inputPasswordValue.value.length < 8
}
</script>
<template>
<div>
<h2>
Enter password
</h2>
<input
type="password"
:class="{
'input-password': true,
'invalid-password': isInputInvalid
}"
v-model="inputPasswordValue"
@keyup="checkInputValidity" />
<p v-if="isInputInvalid">
Password should be at least 8 characters long!
</p>
</div>
</template>
<style scoped>
.input-password {
font-size: 16px;
letter-spacing: 3px;
padding: 4px 6px;
outline: none;
border: 1px solid #000;
}
.invalid-password {
border: 1px solid red;
}
</style>
Code language: HTML, XML (xml)
In the above code, we have two reactive states named isInputInvalid and inputPasswordValue.
The default state of isInputInvalid is false. However, with every keyup event, we call the checkInputValidity method declared on line 7. We check if the length of inputPasswordValue is less than 8 then we assign it false.
You can a working version of the above code from my repo links below: