I'm building a basic 'required' form validation function. Here's the function:
JS:
export default {
methods: {
required(string) {
if (!string) {
return 'This field is required!'
}
}
}
}
HTML:
<input id="username"
v-model="credentials.username"
type="text"
name="username"
/>
<span>{{ required(credentials.username) }}</span>
The above works great. If I start typing in the input, the returned value goes null. If I empty the input, the returned value comes back as expected, "This field is required".
My question is, how can I return the value as null/blank to start? Expected flow is:
One solution is to use an input
-event handler (called for every new value in the input) that sets a flag to indicate the field is "dirty". Then conditionally render the validation result (the <span>
) based on the flag:
Declare a data property named "dirty"
:
export default {
data() {
return {
dirty: false,
}
}
}
In the template, add an input
-event handler on the <input>
that sets the dirty
flag:
<input @input="dirty = true">
Also, conditionally render the <span>
field based on dirty
:
<span v-if="dirty">{{ required(credentials.username) }}</span>