logaretm / vee-validate

✅ Painless Vue forms
https://vee-validate.logaretm.com/v4
MIT License
10.81k stars 1.27k forks source link

Question: Validate array of values or return just one value #1398

Closed HunterJS-bit closed 6 years ago

HunterJS-bit commented 6 years ago

Hello guys Im new to vee-validate and I would need some help I have a custom multiselect compoent and I would like to add validate to inputs but how can I do that ?? SInce my component is returning array of objects ?? A would like to validate just the value that person is typing ??

andreasvirkus commented 6 years ago

I've also got a similar question. For example, how could I enhance this vue-multiselect example by @logaretm to validate either the objects or even an array of strings (if the options were plain text)?

https://jsfiddle.net/logaretm/c4o5eymv/4/

logaretm commented 6 years ago

You could create custom rules that can validate objects, and you can base them on the built-in rules by importing what you need, something like this would work:

import { Validator } from 'vee-validate';
import { min } from 'vee-validate/dist/rules';

Validator.extend('objectMin', (value, [prop, minLength]) => {
  return min(value[prop], [minLength]);
});

Then use it like this:

<input v-validate="required|objectMin:subCateogry,3">

Having said that you could go further and proxy all rules the same way with an additional argument:

import { Validator } from 'vee-validate';
import * as veeRules from 'vee-validate/dist/rules';

Validator.extend('object', (value, [prop, ...rules]) => {
  return rules.every(rule => {
    return veeRules[rule](value[prop]);
  });
});

However, you would still need to figure a way to pass arguments to rules. This could be a future enhancement.

Validating what the person is typing is a different story, you have to identify the value, is it the finished value after the user has added the tag? or is it what they are typing right now? the latter is unlikely. Your custom component could use v-validate on its internal input. That way you can validate both the input the user is typing and the finished value which will be validated by the parent.

HunterJS-bit commented 6 years ago

thank you :) :+1: