question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Any way to programmatically add validation

See original GitHub issue

Suppose I have a form with 4 fields username, email, password1, password2. I can successfully validate the username field like this:

<div class="md:w-2/3">
        <input
          v-model="username"
          v-validate="'required'"
          name="username"
          :error-messages="errors.collect('username')"
          class="some-class"
          type="text"
          required>
          <span v-if="errors.has('username')" class="error">{{ errors.first('username') }}</span>
      </div>

Do I have to repeat this for email, password1, and password2?

<span v-if="errors.has('field')" class="error">{{ errors.first('field') }}</span>

I’m getting the errors from an API backend so I don’t need to define anything custom for each field?

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:10 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
logaretmcommented, Jul 6, 2019

Typically you would abstract the repetitive logic in a component since vee-validate does not know which element to display the errors in and it can be very complex depending on the UI so no defaults can be made.

You can wrap the logic in a component, and I suggest you use the ValidationProvider and ValidationObserver components instead of the v-validate directive.

Something like this can be very efficient:

<ValidationProvider :rules="rules" v-slot="errors">
        <input
          v-model="value"
          name="username"
          class="some-class"
          type="text"
          required>
          <span v-if="errors[0]" class="error">{{ errors[0] }}</span>
</ValidationProvider>

There are quite a few examples of how you would refactor them.

0reactions
MrToxycommented, Dec 3, 2019

The validation provider does not expose anything on your Vue instance, so you need to use refs to add errors to the provider like this:

<ValidationProvider ref="provider"

Then in your JS you can do this:

this.$refs.provider.applyResult({
  errors: ['array of string errors'],
  valid: false,
  failedRules: {} // you can leave this empty
});

You can find this in the docs

This is a terrible solution if you have dynamically created validation observers in a form. When using a validation observer we should have direct access to the fields in order to be able to set this up instead of having manually set refs for everything.

And the proposed solution becomes even more cumbersome when you have multiple validation providers with the same name…

One workaround if you’re using ValidationObservation and provider and have fields with different names vid’s is:

	computed: {
	  errorFields() {
	    const options = Object.entries(this.$refs.observer.refs).reduce(
	      (acc, [key, {
	        name,
	        applyResult
	      }], i) => {
	        acc[name] = (errors, options = {}) =>
	          applyResult({
	            errors,
	            valid: false,
	            failedRules: {},
	            ...options,
	          });
	        return acc;
	      }, {}
	    );
	    return options;
	  },
	},
	};

Where the this.$refs.observer is the ref you’d place on your validation observer.

And to use if you’d just do this.errorFields.<name_of_field>([errors], {options}) I would re-open this issue since there’s really no good solution out there

Read more comments on GitHub >

github_iconTop Results From Across the Web

In Angular, how to add Validator to FormControl after control is ...
A simple solution would be to first get all the validators in the form control and assign a new validatorFn to it when...
Read more >
Adding validator control programmatically - MSDN - Microsoft
Any ideas ? The way I add the validators is by creating an instance, giving values to all relevant properties, and then adding...
Read more >
Implementing Validation and Business Rules Programmatically
Method validators are the primary way of supplementing declarative validation rules and Groovy-scripted expressions using your own Java code. Method validators ...
Read more >
How to add custom validations to fields programmatically?
If you want custom validation for a different field then, 1. Replace the word “text” in the above code with the field name...
Read more >
Add values to a regular drop-down list programmatically
In this tutorial, I am going to show you how to add values to a drop down list ... 'Apply data validation to...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found