[Vuejs]-Form validation not working while implementing an if statement

0πŸ‘

βœ…

Oh, second round.

In your if, your condition is off. You check if the form is valid with !a && !b && !c && !d, meaning that all the values have to be empty for the form to be valid. But you want the opposite, i.e. a && b && c && d:

  methods: {
    submit() {
      if (
        this.firstName &&
        this.lastName &&
        this.paymentAmount &&
        this.accountNumber
      ) {
        this.isFinalStep();
      } else {
        alert("please fill the required fields");
      }
    },
  },

Note however, that you use provide/inject to inject strings into your components, but you cannot update the source by overriding an injected string – you will just override your local reference.

To avoid this, you should use refs:

  provide() {
    return {
      firstName: ref(this.user_detail1.firstName),
      lastName: ref(this.user_detail1.lastName),
      ...
    };
  },

Now you inject objects, whose value you can override (your if then changes to if(this.firstName.value && this.lastName.value ...).

Bundling all the variables in one userDetails object would probably make things easier for you.

Also note that injected properties are available on the instance, you don’t need to re-declare them in data – you can remove all those:

  data() {
    return {
      firstName: this.firstName,
      lastName: this.lastName,
      paymentAmount: this.paymentAmount,
      accountNumber: this.accountNumber,
    };
  },

In general, I am not sure if you are doing yourself a favor by heavily using provide/inject. In my experience, the gain in comfort does not make up for the loss of visibility. And not using it forces you to use structures that are often better than the one enabled by provide/inject.

For example, in your code, the Button component is doing validation and ultimately navigation (by changing isFinalStep). But those are functionalities that belong to the form, not the button, which basically should just signal the form that the user wants to go on.

A second example is how you use provide/inject to get around emitting messages. Instead of your button signaling a parent that it was clicked, it changes a switch (isFinalStep), which then will trigger changes at an undisclosed location. This will predictably get you into software hell, when you end up with tons of switches scattered around your system, being pressed anywhere, impacting things you cannot oversee anymore.

Long story short, if I were you, I would move the code from App into a new component, i.e. UserDataForm or so, which manages the form data, binds it to its child components, listens to their events, and on submit does validation and saving. Finally, it would trigger navigation, either by emitting an event or by using router.

But that is just a though, others might disagree. Sorry for the long post. Hope it helps.

Leave a comment