Skip to content

Instantly share code, notes, and snippets.

@dacastro4
Created November 27, 2022 01:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacastro4/00d48f86584b13e7f21e7098bf27854d to your computer and use it in GitHub Desktop.
Save dacastro4/00d48f86584b13e7f21e7098bf27854d to your computer and use it in GitHub Desktop.
Laravel Vue Error Handling Class
export default class FormErrors {
errors = []
constructor(errors = []) {
this.errors = errors
}
/**
* Returns the first message from key
*
* @param {string} key
* @param {string | null} def
*/
first(key, def = null) {
if (this.errors.hasOwnProperty(key)) {
return this.errors[key][0]
}
return def
}
/**
* Returns the all messages from key
*
* @param {string} key
*
* @return {string | null}
*/
get(key) {
if (this.errors.hasOwnProperty(key)) {
return this.errors[key]
}
return null
}
/**
* Checks if error exists
*
* @param {string} key
*
* @return {boolean}
*/
has(key) {
return this.errors.hasOwnProperty(key)
}
/**
* @param {Array} errors
*/
record(errors) {
this.errors = errors
}
/**
* Clears errors
*/
clear() {
this.errors = []
}
}
@dacastro4
Copy link
Author

Usage

<label for="email">E-mail</label>
<input name="email" v-model="auth.email" id="email" :class="{'border border-red-600': errors.has('email')}"/>
<span class="text-red-500 text-xs italic mt-1 ml-4" v-if="errors.has('email')">{{ errors.first('email') }}</span>

Using in Vue component

<Field type="password"
       name="password"
       v-model="auth.password"
       label="Password"
       :error="errors.first('password')"
/>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment