3

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!'
4

1 回答 1

2

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:

  1. Declare a data property named "dirty":

    export default {
      data() {
        return {
          dirty: false,
        }
      }
    }
    
  2. In the template, add an input-event handler on the <input> that sets the dirty flag:

    <input @input="dirty = true">
    
  3. Also, conditionally render the <span> field based on dirty:

    <span v-if="dirty">{{ required(credentials.username) }}</span>
    

demo

于 2021-06-12T06:13:33.933 回答