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

laravel-like-vue-validator

v1.0.5

Published

An input validator mixin inspired by Laravel's validator

Downloads

11

Readme

A Vue validator inspired by Laravel's Validator API

A simple input validator designed to be a mixin for Vue components. Simply register the variables and rules with the validator and you get automatic error detection. Supply the validator with an array of error messages and those can be easily injected into the DOM as feedback for the user.

Installation

Grab it on npm with an npm install --save laravel-like-vue-validator

Grab it in src/Validator.js and drop it wherever you keep your mixins.

Usage

Registering Variables

Firstly, tell the validator which variables should be watched. You have a few options here:

this.name = 'validator'

this.location.zip = '07720'

this.users = [
	{ name: 'Bob', email: '[email protected]' },
	{ name: 'Wendy', email: '[email protected]' }
]


this.registerErrorChecking('name', 'required', 'Enter a name');
this.registerErrorChecking('location.zip', 'required|size:5', ['Enter a zip', 'Invalid zip'])
this.registerErrorChecking('users.*.email', 'email', 'Invalid email')

Much like Laravel, you declare the rules you want the inputs to follow as pipe delimited strings. Comma-separated arguments are added after a colon in the rule string.

rules = {
	'required': 	'The input must not be empty',
	'boolean': 		'The input must be a boolean',
	'string': 		'The input must be a string',
	'number': 		'The input must be a number',
	'array': 		'The input must be an array (object)',
	'alpha_num': 	'The input must be an alphanumeric string',
	'email': 		'The input must be a valid email'
	'regex': 		'The input must match a given regular expression',
	'max': 			'The input must be less than or equal to a given value in value or length',
	'min': 			'The input must be greater than or equal to a given value in value or length',
	'size': 		'The input must be exactly a given value in value or length',
	'equals': 		'The input must be equal to a given value',
	'in': 			'The input must be equal to one of the given arguments',
}

examples = [
	'required|alpha_num',
	'email',
	'required|in:yes,no,maybe',
	'string|regex:^[0-9]{1,2}$',
]

The regex rule currently does NOT support pipes within your expression argument. This is due to the fact that the rules string is parsed according to pipe delimiters.

Any arguments that return something truthy from parseFloat(arg) are saved as numbers and not strings.


Error checking

Automatic

By default, whenever Vue detects a change, the validator will automatically re-run error checking on that variable. You can switch to manual error checking with an optional fourth argument.

this.me = 'Dan'
this.you = 'github'

this.registerErrorChecking('me', 'required', 'Enter something')
this.registerErrorChecking('you', 'required', 'Enter something', false)

this.me = ''
this.you = ''

console.log(this.errors.me) 	// 'Enter something'
console.log(this.errors.you) 	// ''

Manual

The errorCheck() function returns the number of detected errors. There are quite a few ways to use the errorCheck() function, but it all comes down to your desired scope.

Check all registered variables
this.name = ''
this.email = 'cats';

this.registerErrorChecking('name', 'required', 'Enter a name')
this.registerErrorChecking('email', 'email', 'Invalid email')

var errors = this.errorCheck() 

console.log(errors)				// 2
console.log(this.errors.name) 	// 'Enter a name' 	
console.log(this.errors.email) 	// 'Invalid email' 	
Check only a specific variable
this.name = ''
this.email = 'cats';

this.registerErrorChecking('name', 'required', 'Enter a name')
this.registerErrorChecking('email', 'email', 'Invalid email')

var errors = this.errorCheck('name')

console.log(errors)				// 1
console.log(this.errors.name) 	// 'Enter a name' 	
console.log(this.errors.email) 	// '' 	
Check a specific key on a variable
this.location = { 
	city: { 
		name: 'Bradley Beach, NJ',
		zip: '984'
	}
}

this.registerErrorChecking('location.city.name', 'required', 'Enter your city')
this.registerErrorChecking('location.city.zip', 'required|size:5', ['Enter a zip', 'Invalid zip'])

var errors = this.errorCheck('location.city.zip') 

console.log(errors)								// 1
console.log(this.errors.location.city.name) 	// '' 	
console.log(this.errors.location.city.zip) 		// 'Invalid zip' 	
Check a specific index in an array
this.users = [ 
	{ 
		name: 'Bob Example',
		email: 'bob@'
	},
	{ 
		name: 'Wendy Example',
		email: 'wendy@example'
	},
]


this.registerErrorChecking('users.*.email', 'required|email', 'Invalid email')

var errors = this.errorCheck('users.1.email') 

console.log(errors)							// 1
console.log(this.errors.users[0].email) 	// '' 	
console.log(this.errors.users[1].email) 	// 'Invalid email' 	

Manually assigned error messages

For the people who want to manually control a message in this.errors, but want their error checking declarations to look consistent

this.name = {
	first: '',
	last: '',
}

this.manualErrorChecking('name.first');
this.manualErrorChecking('name.last', 'Invalid lastname'); // optional default

console.log(this.errors.name.first) // ''
console.log(this.errors.name.first) // 'Invalid lastname'

Applications

Displaying in the DOM

Since Vue is reactive, you can very easily attach error messages near inputs.

<div>
	<input type="text" v-model="name">
	<span class="form-error">{{ errors.name }}</span>
</div>

Checking before Submitting

Simply place the following code into your submit() method and you are sure to have valid inputs!

/**
 * Make POST request
 */
submit() 
{
	if (this.errorCheck() > 0) {
		return
	}

	//
}

Putting it all together

import Vue from 'vue'
import Validator from 'laravel-like-vue-validator'

const vm = new Vue({
	template: '<div></div>',
	mixins: [ Validator ],
	
	data: function()
	{
		return [
			users: [
				{ name: 'Bob', email: '[email protected]' },
				{ name: 'Wendy', email: 'bob@example' }, 	// note the error
			],
			
			location: {
				city: {
					name: 'Bradley Beach',
					zip: '070' 				// ouch, another one
				}
			}
		];
	},
	
	created: function()
	{
		this.registerErrorChecking('users.*.name', 'required|max:50', ['Enter a name', 'Quit lying'])
		this.registerErrorChecking('users.*.email', 'required|email', 'Bad email')
		
		this.registerErrorChecking('location.city.zip', 'required|size:5|number', 'Invalid zip')
		this.registerErrorChecking('location.city.name', 'required|string', 'Enter your city')
	},
	
	ready: function()
	{
		var errors = this.errorCheck();
		
		console.log(errors) // 2
		
		console.log(this.errors[1].email) 			// 'Bad email'
		console.log(this.errors.location.city.zip) 	// 'Invalid zip'
		
	}
})

Testing

The repo comes prepared for a karma-jasmine test suite. Run npm run test-build in the repo root followed by karma start.