Search code examples
javascriptvue.jsvuelidate

Is it possible to re-use a computed property by passing a parameter (Vuelidate)


I'm using Vuelidate for a form that has multiple sections. Each of these sections has formData object and name. Nested inside each of these is a ZIP object to validate zip code with numerous validations....required, numeric, minlength, and maxlength. What I would like to do is have ONE computed property zipCodeValid() and use on both. As of now I have two different computed properties targeting each section which is not terrible but I would like to see ONE reused for a cleaner approach.

Zip validation:
 zip: {
            required,
            numeric,
            minLength: minLength(5),
            maxLength: maxLength(5),
          }




   computed: {
        sectionOneZipValid() {
          return (
            (this.$v.formData.secOne.zip.$dirty &&
              !this.$v.formData.secOne.zip.numeric) ||
            (this.$v.formData.secOne.zip.$dirty &&
              !this.$v.formData.secOne.zip.minLength) ||
            (this.$v.formData.secOne.zip.$dirty &&
              !this.$v.formData.secOne.zip.maxLength)
          )
        },
  sectionTwoZipValid() {
          return (
            (this.$v.formData.secTwo.zip.$dirty &&
              !this.$v.formData.secTwo.zip.numeric) ||
            (this.$v.formData.secTwo.zip.$dirty &&
              !this.$v.formData.secTwo.zip.minLength) ||
            (this.$v.formData.secTwo.zip.$dirty &&
              !this.$v.formData.secTwo.zip.maxLength)
          )
        }
    }

Solution

  • Yes you can pass an argument like this..

    computed: {
            sectionZipValid() {
              return sec => {  return (
                (this.$v.formData[sec].zip.$dirty &&
                  !this.$v.formData[sec].zip.numeric) ||
                (this.$v.formData[sec].zip.$dirty &&
                  !this.$v.formData[sec].zip.minLength) ||
                (this.$v.formData[sec].zip.$dirty &&
                  !this.$v.formData[sec].zip.maxLength)
              )}
            },
        }
    

    and it can be called as

    sectionZipValid('secOne') 
    
    OR
    
    sectionZipValid('secTwo')