npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@primitivesocial/ps-validation

v1.0.11

Published

Vue data validation rules, very much inspired from Laravel validation

Downloads

21

Readme

GitHub Workflow Status CodeFactor downloads min-size license

A Vue plugin that provides out-of-the-box data validation rules, very much inspired from Laravel validation system.

Installation

npm i @primitivesocial/ps-validation
import PsValidation from "@primitivesocial/ps-validation";
Vue.use(PsValidation);

Basic Usage Example

The plugin provides a data property validator that creates a new instance of the validator.

In this simple example, we will demonstrate how to add a validation for name property before submitting the data using the method submitData().

// Vue SFC
export default {
   data() {
      return {
          name: '',
      }
   },
   methods: {
      submitData() {
         axios.post(url, { data: { name: name} });
      }
   }
}
  • First step define the validation rules needed
export default {
   data() {
      return {
         name: '',
         // here we are adding the validation rules
         validationRules: [
            { model: 'name', rules: 'required' },
         ]
      }
   }
}
  • Next we will setup the validator and validate our data before submitting it
   mounted() {
      this.$initValidator();
      this.validator.setRules(this.validationRules);
   },
   methods: {
      submitData() {
         this.validator.validate();
         
         if(this.validator.passes())
            axios.post(url, { data: { name: name} });

         // You can also use .fails()
         if(this.validator.fails())
            alert('Name is required');
      }
   }

And that's it! 🦄 🦄 🚀 🚀

Error rendering & Customization

The plugin provides a helper $error to render the error in the Vue component template. Each rule has a default error message.

<span class='error'>{{ $error('name') }}</span> 
<!-- Will display "this field is required" for the required rule. -->

You can customize the error message when setting up the validator.

this.validator
   .setCustomMessages({
      'name': 'The name field must not be empty.'
   });

Note: the key provided in the setCustomMessages() object parameter, is always set to: data property concatenated with rule name

Support for dot path annotations

You can validate deep nested properties inside your data object easily by adding dot path annotations.

data() {
   return {
      event: {
         speaker: {
            name: '',
         }
      },
      validations: [
         {model: 'event.speaker.name', rules: 'required'}
      ]
   }
}

Working With Rules

Adding multiple rule

You can add multiple rule to the same property or model by separating them with |

{ model: 'age', rules: 'required | integer | min:18' }

Available rules

  • required The field under validation must be present in the input data and not empty
  • integer The field under validation must be an integer
  • email The field under validation must be a valid email
  • string The field under validation must be an string
  • date The field under validation must be a date
  • min:value The field under validation must have a minimum value. Numbers are only evaluated for now
  • max:value The field under validation must have a maximum value. Numbers are only evaluated for now
  • before_or_equal:date The field under validation must be a value preceding or equal to the given date
  • after_or_equal:date The field under validation must be a value after or equal to the given date
  • required_if:boolean The field under validation must be present and not empty if the boolean condition is true
  • credit_card_number:cardType The field under validation must be a valid credit card number of the specified type
  • credit_card_cvv The field under validation must be a valid credit card cvv

*Available credit card types for validation: Visa, MasterCard, Amex, VisaElectron

// example of combined rules 
data() {
   person: {
      is_student: false,
      age: null,
      registered_at: null,
   },
   card: {
      number: null,
      cvv: null,
      type: 'Visa'
   },
   registration_ends: '10/31/2020',
   validations: [
      // age will be required only if is_student is true
      { model: 'person.age', rules: 'required_if:person.is_student | integer | min:18' } ,
      // registered_at will be required, must be a date and before or equal to registration_ends date
      { model: 'person.registered_at', rules: 'required | date | before_or_equal:registration_ends' },
      // credit card number and cvv validation
      { model: 'card.number', rules: 'credit_card_number:card.type' },
      { model: 'card.cvv', rules: 'credit_card_cvv' }, 
   ]
}

Adding Custom rule

You can easily extend the validator by adding a custom rule using the method extend(ruleName, function, errorMessage)

mounted() {
   this.validator.extend(
      'alpha_dash',
      function(value, arg) {
         let regexp = /^[a-z_]+$/i;
         return !!regexp.test(value);
      },
      'this field must contain only letters as well as underscores.'
   );
},
data() {
   return {
      username: '',
      validations: [
         { model: 'username', rules: 'string | alpha_dash' }
      ]
   }
}

Developer friendly

Along with the jest tests, the plugin provides helpful warning messages in the browser console in case something is missed by the developer. Here are few examples:

When you try to validate without setting the rules to the validator

PsValidation debugger: You must specify the validation rules.

Or when you add a rule that doesn't exist or not defined.

PsValidation debugger: The rule wtv for the model noticeEvent.notifyDate is not defined. It will be ignored.

Author & Contribution

Hey, I'm Elie Andraos, a web developer at Primitive Social. Pull requests are always welcome. For major changes, please open an issue first to discuss what you would like to change. You can also reach me out on twitter for any question!