1
votes

My real case is like this : https://codepen.io/positivethinking639/pen/ZEEaOqy?editors=1010

The vue component like this :

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data: () => ({

    selectedCountry: null,
    dataCountry: [
      { name: 'England', id: 1 },
      { name: 'Spain', id: 2 },
      { name: 'Italy', id: 3 },
    ],
    selectedClub: null,
    dataClub: [
      { name: 'Chelsea', id: 1 },
      { name: 'Madrid', id: 2 },
      { name: 'Juventus', id: 3 },
    ],
    playerName: null,
    playerNameRules: [
        // v => !!v || 'Name is required',
        v => (v && v.length >= 3) || 'Player name at least 3 characters',
    ],
    countryRules: [
        v => !!v || 'Country is required',
    ],
    clubRules: [
        v => !!v || 'Club is required',
    ],
    validSearch: false,

  }),

  methods: {
    searchPlayer() {
        if (this.$refs.formSearch.validate()) {
          console.log('validate form success')
        }
        else
          console.log('validate form failed')
     }
  }
})

so I want the user to be able to search by player name or the user can also search by country and club

if the user enters the player name and clicks the search button, validation is successful. vice versa if the user enters country and club, then click search, it passes validity

so the user can choose one of them to search. but if the user click the search button without selecting one, it displays validation failed

How can I do it?

2

2 Answers

1
votes

You can have N number of rules for any number inputs in a form, but this a special case where you need to have any one of them to search a player

Instead of form.validate(form validation validates for each input field based on the rules and independent to the field), In your case you can manually validate as per your requirements by accessing your data

methods: {
    searchPlayer() {
      var playerCondition = this.playerNameRules[0](this.playerName) == true;
      var countryClub = this.countryRules[0](this.selectedCountry) == true && this.clubRules[0](this.selectedClub) == true;
      if(this.playerName && this.playerName.length < 3) {
        playerCondition = false;
        countryClub = false;
      }
        if ((playerCondition) || (countryClub)) {
          console.log('validate form success')
        }
        else
          console.log('validate form failed')
     }
  } 

Working codepen here: https://codepen.io/chansv/pen/abbVGRx?editors=1010

0
votes

Use computed property for club and country rules. In function body you can check if another option is selected.

  computed: {
    clubRules() {
      return [
        v => (!!v || !!this.selectedCountry) || 'Club is required',
      ];
    } 
  },