Vee-validate: how to validate json

Created on 31 Oct 2018  ยท  4Comments  ยท  Source: logaretm/vee-validate

how to validate json either by using validation rules or custom rules

Please help me it's urgent

THanks

โ” question

All 4 comments

The docs explains that rules accepts whatever value reported (dispatched/emitted) by the input, so if you have an input that emits an object for example, your rule needs to be aware of your object structure:

import { Validator } from 'vee-validate';

// This rule checks if a prop within a json object has a minimum length of x
Validator.extend('json_min', {
  validate (value, [prop, min]) {
    if (!value || !value[prop]) return false;

    return value[prop].length >= min;
  }
});

You can extend most vee-validate rules in the same way:

import { Validator } from 'vee-validate';

// proxy any rule to be able to validate any prop within a json object
Validator.extend('json', {
  validator (value, [rule, prop, ...args]) {
    if (!value) return false;

    return Validator.rules[rule].validate(value[prop], args);
  }
});

You can then use it like this:

<input type="text" name="field" v-validate="'required|json:min,propName,3'"

Not very clean but this is one way to do it, generally you want your inputs to have primitive values and avoid validating JSON objects since it adds another level of complexity.

can you please elaborate with example

Thanks Bro Mr @logaretm

I finally i got answer please find out below one by using custom validation

or

VeeValidate.Validator.extend('json', {
getMessage: field => 'The '+ field +' field must be a valid ' + field,
validate: value => {
try {
JSON.parse(value);
return true;
} catch (error) {
return false;
}
}
});

@logaretm I need this rule but cant find out how to run it. I got error.
please help with working code the same rule

Was this page helpful?
0 / 5 - 0 ratings

Related issues

YamenSharaf picture YamenSharaf  ยท  3Comments

schel4ok picture schel4ok  ยท  3Comments

kidox picture kidox  ยท  3Comments

Etheryte picture Etheryte  ยท  3Comments

parweb picture parweb  ยท  3Comments