Search code examples
vue.jsvuelidate

Vuelidate required champ input Email OR NumberMobile


i would like to know how I can validate the form once the phone number or email address has been completed. I don't really understand how to use or with vualidate, I looked at the document and some forum I didn't find someone in the same case as me.
My code : https://www.noelshack.com/2022-27-5-1657285356-screen1.png
Error : http://www.noelshack.com/2022-27-5-1657285360-screen2.png
If anyone can help me please <3


Solution

  • There is several ways to do it, what you can do is to make email and phone to required BUT you have another property hasProvidedAtLeastOneContact that check if at least one of them has a value.

    <script>
    import useVuelidate from '@vuelidate/core'
    import { required, email } from '@vuelidate/validators'
    
    import { helpers } from '@vuelidate/validators'
    
    const phoneValidator = (value) => !helpers.req(value) || value.includes('01') // customize here your validator
    
    
    export default {
      setup () {
        return { v$: useVuelidate() }
      },
      data () {
        return {
          firstName: 'Jack',
          lastName: 'Smith',
          contact: {
            email: '',
            phone: ''
          }
        }
      },
      computed: {
        hasProvidedAtLeastOneContact() {
            return !!this.contact.email || !!this.contact.phone
        }
      },
      methods: {
        async validate() {
            console.log(await this.v$.$validate())
        }
      },
      validations () {
        return {
          firstName: { required }, // Matches this.firstName
          lastName: { required }, // Matches this.lastName
          contact: {
            email: { email }, // Matches this.contact.email
            phone: { phoneValidator } // Matches this.contact.phone
          },
          hasProvidedAtLeastOneContact: {
            isTrue: (value) => value
          } // Matches this.hasProvidedAtLeastOneContact
        }
      }
    }
    
    </script>
    
    <template>
        <div>
            <p>Form</p>
            <input v-model="firstName">
            <input v-model="lastName">
            <input v-model="contact.email">
            <input v-model="contact.phone">
            <button @click="checkValidation">Validate</button>
        </div>
    
    </template>
    
    

    You can also have a similar result with dynmamic rules but I think it's a bit more complex https://vuelidate-next.netlify.app/examples.html#dynamic-validation-schema