validationvuejs3vuetify.js

How to ensure all items in a v-combobox follow rule


I have a v-combobox which allows the user to select from a list of email addresses or add new ones that arent in the list. The issue is the rule does not apply to all items in the list. So if there is a new item added that the email is not valid but there is a valid entry already then it fails. I need the validation rules to check every item in the array. This is what I had tried:

                    <v-combobox
                    color="primary"
                    label="To"
                    :items="stateData && stateModel ? stateData.find(item => item.state_id == stateModel?.state_id)?.state_contacts : []"
                    item-title="email_address"
                    v-model="toModel"
                    :rules="emailRule"
                    chips
                    multiple
                    variant="outlined"/>

and the rule is as follows:

  const emailArrayRule = [ (e: any, value: string) => /.+@.+/.test(value) || 'Invalid Email address' ]

Can this be done using the rules notation above or do I need to manually loop through each array and create a custom function that triggers a failure? Interested in how to approach this.


Solution

  • value in your rule is not a string, but is an array of strings. The regex test function coerces the array into a single string using Array.toString().

    a value of

    ['some@email.com', 'notanemail']
    

    is then tested as

    'some@email.com,notanemail'
    

    Your test looking for a single @ character then returns true. You will need to loop the array instead of letting regex coerce it into a string.

    const emailRule = [ (values: string[]) => {
      if (!values) return true
      for (const val of values) {
        if(!/.+@.+/.test(val)) return 'Invalid Email address'
      }
      return true
    }]
    

    Vuetify Playground example