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-vue-form-validator

v0.2.1

Published

An easy way to validate forms using back end logic

Downloads

192

Readme

An easy way to validate forms using backend logic.

Latest Version on NPM Software License npm npm

🔥 If you use Laravel, this package matches perfectly with andersao/l5-repository.

This package helps you quickly to build requests for REST API. Move your logic and backend requests to dedicated classes. Keep your code clean and elegant.

Wouldn't it be great if you could just use your back end to validate forms on the front end? This package provides a BaseProxy class that does exactly that. It can post itself to a configured endpoint and manage errors. The class is meant to be used with a Laravel back end and it doesn't limit that you need only to work with laravel, Ruby on Rail, NodeJs, ExpressJs, or any other languages.

Take a look at the usage section to view a detailed example on how to use it.

Install

You can install the package via yarn (or npm):

npm install laravel-vue-form-validator
yarn add laravel-vue-form-validator

Usage

import Vue from 'vue'
import FormValidator from 'laravel-vue-form-validator'

Vue.use(FormValidator)

Nuxt Support

Put it on top of axios module

export default {
    modules: [
       'laravel-vue-form-validator/nuxt',
       '@nuxtjs/axios',
    ]
}

Note:

baseURL is required. You can define baseURL at .env just one of them

API_URL=http://localhost::3000/api
API_HOST=http://localhost::3000/api

if your axios already defined in nuxt.config.js

export default {
    axios: {
        baseURL: process.env.API_URL
    }
}

Advance usage

-------------- Todo --------------

Vue plugins

import Vue from 'vue'
import FormValidator from 'laravel-vue-form-validator'

Vue.use(FormValidator)

Note

Error response must look like:

{
    "errors": {
        "field": [
            "The field is required."
        ]
    }
}

It will create $errors object inside components.

Methods are available:

Validator | Description --------------------------- | -------------------------------------- has(field = null) | check specific field error first(field) | get message by field name. missed(field = null) | check if there is no any error of given field name. nullState(field = null) | false|null of given field. any() | check if any errors exist. get(field) | get specific field. all() | get all errors. fill(errors = {}) | fill the errors object. flush() | clear all errors. clear(field) | clear specific error by field name. onKeydown(event) | event to clear error by event.target.name. (input the has name).

Using with Vuex

1.Create proxies folder

~/proxies/NewsProxy.js

import { BaseProxy } from 'laravel-vue-form-validator'

class NewsProxy extends BaseProxy {
  constructor(parameters = {}) {
    super('news', parameters)
  }
}

export default NewsProxy

2.Store

  • Create news store
  1. actions.js
  2. getters.js
  3. mutation-types.js
  4. mutations.js
  5. state

actions.js

import { ALL } from './mutation-types'
import { NewsProxy } from '~/proxies'
import { NewsTransformer, PaginationTransformer } from '~/transformers'
import { pagination, notify } from '~/utils'

const proxy = new NewsProxy()

const all = async ({ commit, dispatch }, payload = {}) => {
  const { fn } = payload
  if (typeof fn === 'function') {
    await fn(proxy)
  }
  try {
    const { data, meta } = await proxy.all()
    const all = {
      items: NewsTransformer.fetchCollection(data),
      pagination: PaginationTransformer.fetch(meta)
    }
    await commit(ALL, all)
  } catch (e) {
    const data = { items: [], pagination }
    await commit(ALL, data)
    await notify({ response: e })
  }
}

export default {
  all
}

getters.js

export default {
  all: (state) => state.all
}

mutation-types.js

export const ALL = 'ALL'

export default { ALL }

mutations.js

import { ALL } from './mutation-types'

export default {
  [ALL](state, payload = {}) {
    const { items = [], pagination = {} } = payload
    state.all = items
    state.pagination = pagination
  }
}

state.js

export default () => ({
  all: [],
  pagination: {}
})

How to call in components or pages

  • news.vue pages

It can be called in mounted() or asyncData()

  • asyncData()
export default {
    async asyncData({ app, store }) {
        const { id = null } = app.$auth.user
        await store.dispatch('news/all', {
          fn: (proxy) => {
            proxy
              .setParameters({
                userId: id,
                include: ['categories']
              })
              .removeParameters(['page', 'limit'])
          }
        })
    }
}
  • mounted()
export default {
    mounted() {
        const { id = null } = this.$auth.user
        this.$store.dispatch('news/all', {
          fn: (proxy) => {
            proxy
              .setParameters({
                userId: id,
                include: ['categories']
              })
              .removeParameters(['page', 'limit'])
          }
        })
    }
}

You can set or remove any parameters you like.

Proxy's methods are available

Method | Description --------------------------------------------------- | -------------------------------------- setParameter(key, value) | Set param by key and value removeParameter(key) | Remove param by key setParameters({ key: value, key1: value1 }) | Set params by key and value removeParameters([key1, key2]) | Remove params by keys removeParameters() | Remove all params

if setParameter that value is empty or null it will remove that param for query string

Be sure to use only once in mounted() or asyncData() and asyncData() is only available in NuxtJs

Use proxy in components

  • news/_id.vue pages
import { NewsProxy } from '~/proxies'

const proxy = new NewsProxy()

export default {
    methods: {
        async fetchNews(id) {
            try {
              const { data } = await proxy.find(id)
              this.detail = data
            } catch (e) {
              console.log(e)
            }
        }
    },
    mounted() {
        this.fetchNews(this.$route.params.id)
    }
}

Validations

Can use vue-vlidator for client-side validator that inspired by Laravel. Chantouch/vue-vlidator

Errors methods available

It can be called by this.$errors.**

Method | Description -------------------------------- | -------------------------------------- all() | To get all errors messages has(attribute) | To check an attribute as any error has(attributes) | To check multiple attributes given have any errors first(attribute) | To get errors message by an attribute

Todo

Add tests

Contact

Twitter @DevidCs83