How to apply individual error message in VueJs Element?

vue js error messages
custom validation in vue js
vue form validation
vue form submit
vue get error message laravel
vue regex validation
vue check if input is empty
password and confirm password validation in vuejs

I have a form (http://element.eleme.io/#/en-US/component/form) in application, where I do server side validation. But I have not glu how to add error message for specific inputs.


Each el-form-item needs a prop attribute for the frontend validation to work. They also need a bound error attribute. I just made each the same as the field name for simplicity, like so:

<el-form-item label="Email" prop="email" :error="errors.email">
    <el-input v-model="form.email" type="email"></el-input>
</el-form-item>

Then when the form is submitted I run my validator for the frontend rules (using Element's rules). Right after that I use axios to post to the server (Laravel). I loop through any errors, and update the value in the errors object. Whenever the form is submitted, I clear the errors (if you don't clear them, the errors will not show up on consecutive form submissions).

data() {

    let passwordsMatch = (rule, value, callback) => {
        if ( value != this.form.password )
            return callback(new Error('Passwords do not match'));

        return callback();
    };

    let form = {
        first_name: '',
        last_name: '',
        email: '',
        phone: '',
        password: '',
        password_confirmation: '',
    };

    // copy blank values, not reference
    let errors = {...form};
    let blankErrors = {...form};

    return {

        form,

        errors,

        blankErrors,

        rules: {
            first_name: [
                { required: true, message: 'First Name is required', trigger: 'blur' },
            ],
            last_name: [
                { required: true, message: 'Last Name is required', trigger: 'blur' },
            ],
            email: [
                { required: true, message: 'Email is required', trigger: 'blur' },
                { type: 'email', message: 'Must be an email', trigger: 'blur' },
            ],
            phone: [
                { required: true, message: 'Cell Phone is required', trigger: 'blur' },
                // TODO: finish phone validation
                //{ type: 'number', message: 'Must be a phone number', trigger: 'blur' },
            ],
            password: [
                { required: true, message: 'Password is required', trigger: 'blur' },
            ],
            password_confirmation: [
                { required: true, message: 'Password is required', trigger: 'blur' },
                { validator: passwordsMatch, trigger: 'blur' },
            ],
        },
    }
},

methods: {

    createAccount() {

        this.clearErrors();


        let passed = this.runValidator();

        if (! passed) return;


        axios.post(`/register`, this.form)
            .then(response => {

                EventBus.$emit('user-form-completed', this.form);

                return;

            })
            .catch(error => {

                const errors = error.response.data.errors;

                for (let index in errors) {

                    let error = errors[index][0];

                    this.errors[index] = error;
                }
            });
    },


    clearErrors() {
        this.errors = {...this.blankErrors};
    },


    runValidator() {

        let passed = false;

        this.$refs.form.validate((valid) => {
            if (valid) passed = true;
        });

        return passed;
    },
},

Simple Vue.js Form Validation with Vuelidate, In order to test out the various error handling techniques, I decided to use three different kinds of Vue.config.devtools = false; Remember that you can have multiple Vue applications running on one web page at a time. To be frank, send your form to server, get result and apply errors. You can do it for individual inputs to. Like live validation. sorry i can't help any further.


I am using Laravel and I usually do like this, My validation in Laravel controller

    return Validator::make($data, [
        'email' => 'required|email',
        'password' => 'required|min:6',
    ]);

My vue.js code in if error comes

if(error.response.status == 400){
    let errors = error.response.data.errors;
    for(let i in errors){
        document.querySelector("div[for='"+i+"']").innerHTML = errors[i][0];
    }
}else if(error.response.status == 401){
    console.log(error.response);
    let errors = error.response.data;
    document.querySelector("div[for='password']").innerHTML = errors;
}

Complete vue component is

const Login = { 
template: `
    <div class="container">
      <div class="row row-body"> 
        <div class="col-12 col-md-6 offset-md-3">
          <div class="row">
            <div class="col-12 col-md-12 text-center">
              <h1>Login</h1>
            </div>
          </div>
          <div class="row">
            <div class="col-12 col-md-12">
              <form method="POST" action="">

                <div class="row pt-3 pb-3">
                  <div class="col-12 col-md-10 offset-md-1 form-group">
                    <input class="form-control form-rounded" placeholder="Email*" v-model="email">
                    <div for="email" class="text-danger"></div>
                  </div>
                </div>
                <div class="row pb-3">
                  <div class="col-12 col-md-10 offset-md-1 form-group">
                    <input class="form-control" placeholder="Password*" v-model="password" type="password">
                    <div for="password" class="text-danger"></div>
                  </div>
                </div>
                <div class="row pt-3">
                  <div class="col-12 col-md-12 form-group text-center">
                    <button @click="login" class="btn as-btn-outline as-btn-dark mx-2 my-2 my-sm-0 big-btn" type="button">LOGIN</button>
                  </div>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
`,
data(){
    return {
        email: '',
        password: ''
    }
},
mounted(){
    /**/
},
methods:{
        login: function(){
            var formdata = {};
            formdata.email = this.email;
            formdata.password = this.password;
            axios
                  .post('http://far.test/api/login',formdata)
                  .then(response => {
                    console.log(response.data);
                    if(response.data.token !== undefined){
                        this.$parent.is_auth = true;
                        sessionStorage.setItem('asset_token', response.data.token);
                        router.push({ path: '/home' });
                    }
                  })
                  .catch(error => {
                    if(error.response.status == 400){
                        let errors = error.response.data.errors;
                        for(let i in errors){
                            document.querySelector("div[for='"+i+"']").innerHTML = errors[i][0];
                        }
                    }else if(error.response.status == 401){
                        console.log(error.response);
                        let errors = error.response.data;
                        document.querySelector("div[for='password']").innerHTML = errors;
                    }

                  })
                  .finally(() => console.log('finally')/*this.loading = false*/);

        },
    }
}

And related laravel controller methods are

public function validateAuditLogin($data){
     return Validator::make($data, [
        'email' => 'required|email',
        'password' => 'required|min:6',
    ]);
}

public function loginForAudit(Request $request){
    $requestAll = $request->all();
    $pwd = base64_decode($requestAll["password"]);
    for($i=0;$i<4;$i++){
        $pwd = base64_decode($pwd);
    }
    $requestAll['password'] = $pwd;
    $validator =  $this->validateAuditLogin($requestAll);
    if($validator->fails()){
        return response()->json(['errors'=>$validator->messages()],400);
    }
    if ($user = \Auth::attempt(['email' => $requestAll['email'], 'password' => $requestAll['password'] ])) {
        $token = str_random(40);
        User::where('id',\Auth::id())->update(['api_token'=>$token]);
        return response()->json(['token'=>$token]);
    }else{
        return response()->json('Email or password is incorrect',401);
    }
}

Handling Errors in Vue.js, Just apply the v-validate directive on your input and pass a string value which is a When a form validation fails, VeeValidate populates this errors variable with In the code block above, we have 5 input elements which are: toLowerCase()) ? false : !! value, data: { message: `${value} has already been  Such delay is much worse for components than whole pages because we’re not used to wait for individual parts of the UI to appear. When we click a button, we expect a reaction immediately. If nothing happens when we interact with a website, we either perceive the application as slow or broken, and most of us leave the site.


How To Validate Forms in Vue.js, I named the demo vuejs-laravel-validation-error-messages , feel free to name it whatever you like. For this tutorial, we'll be making use of Laravel Elixir . submitted: false, // array to hold form errors errors: [], }, methods: { createPost() { let post = this.post; this. The el tells Vue.js the element to mount on. Being able to change the validation rules on the fly can be a godsend with multi-step forms. Each step has its own rules that validate certain parts of the form data. Vuelidate can use computed properties as validation rules. That means that you can return different rules for each step of a multi-step form.


add a ref with any name and do the following:

In js do this
this.$refs.formData.errorBucket=[]
<v-text-field                                                                  
  ref="formData"
  :rules="[rules.required, rules.max]">
</v-text-field>

Handling Laravel Validation Error Messages With Vue.js ― Scotch.io, In your real Vue application, you might have to install with npm: The v-model directive is added to the select element, not the option elements. VeeValidate allows us to report messages by checking if an error does exist in This is because false is a value and the validation rule will assume the form is  To start using it you will have to manually install velocity-animate & supply the librarty to vue-notification plugin (reason for doing that is to reduce the size of this plugin). In your main.js : import Vue from ' vue ' import Notifications from ' vue-notification ' import velocity from ' velocity-animate ' Vue . use (Notifications, { velocity })


Complete guide to form validation in Vue, Let's first create a standard form, and apply some validation rules to our data. The form element itself has a @submit handler with a prevent modifier Let's start by adding descriptive error messages when an input's validation fails. The $dirty state is a boolean with the value of false by default, when an  The easiest way to try out Vue.js is using the Hello World example. Feel free to open it in another tab and follow along as we go through some basic examples. Feel free to open it in another tab and follow along as we go through some basic examples.


Accessible form error auto-focus with Vuelidate in Vue, Dealing with errors is an integral part of building an application. render the elements in your list due to an unforeseen error on only a single one of we want with it — wrap individual components or entire application pieces  Form validation is natively supported by the browser, but sometimes different browsers will handle things in a manner which makes relying on it a bit tricky. Even when validation is supported perfectly, there may be times when custom validations are needed and a more manual, Vue-based solution may be more appropriate. Let’s begin with a


Handling Errors in Vue with Error Boundaries - Dillon Chanis, In one of the projects I was working on, my backend is written with laravel while and any() but we need to implement something close to that with Vue as well. to display laravel validation errors in vue, although individually , but in my case,  Class and Style Bindings. A common need for data binding is manipulating an element’s class list and its inline styles. Since they are both attributes, we can use v-bind to handle them: we only need to calculate a final string with our expressions. However, meddling with string concatenation is annoying and error-prone.