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:
- Returned value is null/blank to start
- User starts typing, nothing changes because string.length != 0
- User deletes all characters, causing string.length == 0, causing the returned value to be 'This field is required!'
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":In the template, add an
input-event handler on the<input>that sets thedirtyflag:Also, conditionally render the
<span>field based ondirty:demo