logaretm / vee-validate

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

Question: Centralized place for custom validation #430

Closed pimboden closed 7 years ago

pimboden commented 7 years ago

Hello I'm working on a server-based webpage, that has some smalll widgets that act like a kine of Single-Page app.

I always have to use the same custom validators: My question is, how can I do that?

My Idea is that I have a file VueCustomValidators.js There I wolud have my validators

import {Validator} from 'vee-validate'
    const dictionary = {
  en:{
    messages:{
      alpha_extended:() => "Entry is not allowed",
      hslu_email: () => "Email is not an HSLU-Email",
      no_hslu_email: () =>"No HSLU-Email allowed"
    }
  },
  de-ch:{
    messages:{
    alpha_extended:() => "Eingabe ist nicht erlaubt"
    hslu_email: () => "E-Mail ist keine HSLU E-Mail",
    no_hslu_email: () =>"Es darf keine HSLU E-Mail angegeben werden"
  }
  }
}

Validator.updateDictionary(dictionary); 

const  alpha_extended = (value, args) => {
   return !Array.isArray(value) && /^[a-zA-ZàâçéèêëîïôûùüÿñæœÀÂÇÉÈÊËÎÏÔÛÙÜŸÑÆŒäöüÄÖÜß\.\s]+$/.test(value);
};

Validator.extend('alpha_extended',  alpha_extended);

const hslu_email = (value,args) )=>{
  return !Array.isArray(value) && /@hslu\.ch$/ig.test(value);
}
Validator.extend('hslu_email', hslu_email);

const no_hslu_email = (value,args) )=>{
  return !Array.isArray(value) && !/@hslu\.ch$/ig.test(value);
}
Validator.extend('no_hslu_email', no_hslu_email);

Now I would like to use that file... but I don't have any export, so how can I import it...

Do you have an idea how I could do this... Or how do you define your custom validations if they are used in multiple components?

Thanks for the help

logaretm commented 7 years ago

You don't need to import the custom validation each time you need it, as they are installed globally for all components, so you only need to import them once per project or entry file.

You can do something like this to make it more modular:

// myrules.js
const rules = {
  // your custom rules.
};

// export an 'install' function.
export default (Validator) => {
  // for every rule we defined above.
  Object.keys(rules).forEach(rule => {
    //  add the rule.
    Validator.extend(rule, rules[rule]);
  });
};

and so in your main app file:

import { Validator } from 'vee-validate';
import installRules from './myrules';

installRules(Validator);

now you can reuse your file in multiple projects or entry files.

pimboden commented 7 years ago

Thanks... This works!