How to Show Laravel Vue Js Errors - vue.js

I am learning Vue.js I have successfully made this registration form and its working fine
but I'm having a problem in showing errors.
register.vue page
<form #submit.prevent="RegisterUser" aria-label="Register">
<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right">Name</label>
<div class="col-md-6">
<!-- <input id="name" v-model="name" type="text" class="form-control" name="name" value="" required autofocus> -->
<input type="text" v-model="name" class="form-control" required="required" autofocus="autofocus">
</div>
</div>
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">Email Address</label>
<div class="col-md-6">
<!-- <input id="email" v-model="email" type="email" class="form-control" name="email" value="" required> -->
<input type="email" v-model="email" required autofocus class="form-control">
{{ errors.email }}
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">Password</label>
<div class="col-md-6">
<!-- <input id="password" v-model="password" type="password" class="form-control" required> -->
<input type="password" v-model="password" class="form-control" required>
</div>
</div>
<div class="form-group row">
<label for="password-confirm" class="col-md-4 col-form-label text-md-right">Confirm Password</label>
<div class="col-md-6">
<!-- <input id="password-confirm" v-model="password_confirmation" type="password" class="form-control" required> -->
<input type="password" v-model="confirm_password" class="form-control" required>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
Register
</button>
</div>
</div>
</form>
This is my scripts in register.vue page working registration fine
<script>
export default {
// props: ['name'],
data: function() {
return {
name: '',
email: '',
password: '',
confirm_password: '',
errors: {},
};
},
methods: {
RegisterUser() {
axios.post('/register', {
name: this.name,
email: this.email,
password: this.password,
password_confirmation:this.confirm_password
})
.then(function(response){
swal({
title: "Good job!",
text: "Login Success",
icon: "success",
button: "Okay",
})
.then((willDelete) => {
if (willDelete) {
window.location.href = '/home';
}
});
})
.catch(function (error) {
console.log(error.response.data);
});
}
}
}
</script>
This is the Errors I want to fetch...
How to fetch and how this errors on my vue components?

Note!! This solution is based on ES6 so you might have to transpile this to ES5
I had this issue a while back so I wrote a simple class to help manage validation messages from the server. https://gist.github.com/nonsocode/e6f34a685f8be1422c425e3a20a69a4b
You can use it by importing this to your template
import ErrorBag from 'path-to-errorbag-class'
and use it in your data method like so
data: function() {
return {
name: '',
email: '',
password: '',
confirm_password: '',
errors: new ErrorBag,
};
},
In your template, you can check if there's a validation error and then decide how you ant to handle it. I'll assume you're using bootsrap 4
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">Email Address</label>
<div class="col-md-6">
<input type="email" v-model="email" required autofocus :class="{'form-control': true, 'is-invalid': errors.has('email')}">
<div class="invalid-feedback" v-if="errors.has('email')" >{{ errors.first('email') }}</div>
</div>
</div>
in the catch method of your ajax request,
axios(...)
.then(...)
.catch(function (error) {
if (error.response && error.response.status == 422) {
const errors = err.response.data.errors;
this.errors.setErrors(errors);
}
});
After successfully submitting to your server, you can call the clearAll method on the errorbag to clear all errors from the bag

Related

How to clear form after submit in vuejs

I am trying to empty the form after it submits form but I am unable to do this. Here is the code
<form class="form-horizontal" #submit.prevent="addtodirectory" id="form-directory">
<div class="model-body">
<div class="card-body">
<div class="form-group row">
<label for="inputEmail3" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
<input v-model="form.name" type="text" name="name"
class="form-control" :class="{ 'is-invalid': form.errors.has('name') }">
<has-error :form="form" field="name"></has-error>
</div>
</div>
<div class="form-group row">
<label for="inputEmail3" class="col-sm-2 col-form-label">Address</label>
<div class="col-sm-10">
<textarea v-model="form.address" type="text" name="address"
class="form-control" :class="{ 'is-invalid': form.errors.has('address') }"></textarea>
<has-error :form="form" field="address"></has-error>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Profession</label>
<div class="col-sm-10">
<input v-model="form.profession" type="text" name="profession"
class="form-control" :class="{ 'is-invalid': form.errors.has('profession') }">
<has-error :form="form" field="profession"></has-error>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Contact Number</label>
<div class="col-sm-10">
<input v-model="form.contact_number" type="text" name="contact_number"
class="form-control" :class="{ 'is-invalid': form.errors.has('contact_number') }">
<has-error :form="form" field="contact_number"></has-error>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">City</label>
<div class="col-sm-10">
<input v-model="form.city" type="text" name="city"
class="form-control" :class="{ 'is-invalid': form.errors.has('city') }">
<has-error :form="form" field="city"></has-error>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">State</label>
<div class="col-sm-10">
<select v-model="form.state" type="text" name="state"
class="form-control" :class="{ 'is-invalid': form.errors.has('state') }">
<has-error :form="form" field="state"></has-error>
<option value="Rajasthan">Rajasthan</option>
<option value="Gujrat">Gujrat</option>
</select>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-success">Submit</button>
<button type="submit" class="btn btn-default float-right">Cancel</button>
</div>
<!-- /.card-footer -->
</div>
</form>
<script>
export default {
data() {
return {
news:{},
form: new Form({
name : '',
address:'',
profession:'',
city:'',
state:''
})
}
},
methods: { addtodirectory() {
this.$Progress.start();
this.form.post('api/addtodirectory');
Toast.fire({
type: 'success',
title: 'Directory Updated successfully'
})
$('#form-directory input[type="text"]').val('');
this.$Progress.finish();
}
}
I am using vform plugin to submit the form. Using Laravel as backend. The data is being submitted in database but I am not able to clear the form. please help in this regarding. Should I use jquery or javascript to clear the form? I tried different ways but I could not figure out the problem.
Simply empty your form object after form submit.
form: new Form({
name : '',
address:'',
profession:'',
city:'',
state:''
})
Well it was simple and I did following code for emptying the form.
addtodirectory(event) {
this.$Progress.start();
this.form.post('api/addtodirectory');
// document.getElementById("form-directory").reset();
console.log('durgesh');
// document.getElementsByName('name').value = '';
Toast.fire({
type: 'success',
title: 'Directory Updated successfully'
})
this.form.name = "";
this.form.profession ="";
this.form.address="";
this.form.city = "";
this.form.state = "";
this.$Progress.finish();
},
after submitting the form I did not used the form. so after doing this I emptied the form.
Or in a one-liner:
Object.keys(form).forEach(v => form[v] = "")
instead of:
this.form.name = "";
this.form.profession ="";
this.form.address="";
this.form.city = "";
this.form.state = "";

Reload screen after submitting form - Vue.js

I am creating a Discord command creator app. I have the client talking to the server correctly and outputting what I want. The issue is that once I submit the form, the page doesn't refresh. Below I have the template and script.
<template>
<form v-on:submit="addCommand">
<div id="container" class="col-md-5 m-auto">
<div class="card card-body">
<h1 class="text-center mb-3"><i class="fab fa-discord"></i> Command Creator</h1>
<div class="form-group">
<label for="command">Command</label>
<input type="text" v-model="command" class="form-control" placeholder="Please enter a command." />
</div>
<div class="form-group">
<label for="output">Output</label>
<input type="text" v-model="output" class="form-control" placeholder="Please enter an output." />
</div>
<button type="submit" class="btn btn-primary btn-block">Create</button>
</div>
</div>
</form>
</template>
<script>
export default {
name: 'Dashboard',
data () {
return {
command: '',
output: ''
}
},
methods: {
addCommand (e) {
this.axios.post('http://localhost:3000/server', {
command: this.command,
output: this.output
})
e.preventDefault()
}
}
}
</script>

Not entering the created record in the list form in Angular 5

In my home page i have to create records and when i am creating the records and clicking on submit button and getting like added successfully. After that the created record is not available in the list records.When i'm creating another new record and submit it the previous created record is displays in the list.
Type Script code is:
import { Component, OnInit } from '#angular/core';
import {FormControl, Validators, NgForm } from '#angular/forms';
import { VisitService } from '../shared/visit.service';
import { ToastrService } from 'ngx-toastr';
import { Response, RequestOptions, Http, Headers } from '#angular/http';
import { CookieService } from 'ngx-cookie-service';
#Component({
selector: 'app-visit',
templateUrl: './visit.component.html',
styleUrls: ['./visit.component.css']
})
export class VisitComponent implements OnInit {
cookieValue = 'UNKNOWN';
constructor(private visitService: VisitService,private http: Http,private cookieService: CookieService, private toastr: ToastrService ) { }
ngOnInit() {
this.resetForm();
this.cookieValue = this.cookieService.get('session');
console.log('token from browser' + this.cookieValue );
const url = `http://localhost:8080//api/getallvisits/`;
// const headers = new Headers({'Content-Type': 'application/json','Authorization':'Bearer' +this.cookieValue});
let headers = new Headers({ 'Authorization': 'Bearer ' + this.cookieValue });
// const headers = new Headers();
// headers.append('Authorization', 'Bearer' +this.cookieValue );
const options = new RequestOptions({ headers: headers });
return this.http.get(url, options)
.subscribe(res => {
console.log('message from' + res);
// this.refresh();
alert('successfullyyy...');
// console.log('message from' + people.json())
});
}
resetForm(form?: NgForm) {
if (form != null)
form.reset();
this.visitService.selectedVisit = {
'ID':null,
'UserName': '',
'Height': null,
'Weight': null,
'Temperature': null,
'BloodPressure': '',
'PatientNote': '',
'NurseNote': '',
'DoctorNote': '',
}
}
onSubmit(form: NgForm) {
if (form.value.ID == null) {
this.visitService.createVisit(form.value)
.subscribe(data => {
this.resetForm(form);
this.visitService.getVisitList();
this.toastr.success('New Record Added Succcessfully', 'Employee Register');
})
}
else {
this.visitService.updateVisit(form.value.ID, form.value)
.subscribe(data => {
this.resetForm(form);
this.visitService.getVisitList();
this.toastr.info('Record Updated Successfully!', 'Employee Register');
});
}
}
}
And my HTML page is:
<form class="visit-form" #visitForm="ngForm" (ngSubmit)="onSubmit(visitForm)">
<input type="hidden" name="ID" #ID="ngModel" [(ngModel)]="visitService.selectedVisit.ID">
<div class="form-row">
<div class="form-group col-md-6">
<mat-form-field class="example-full-width">
<input class="form-control" matInput placeholder="UserName" name="UserName" #UserName="ngModel" [(ngModel)]="visitService.selectedVisit.username"
placeholder="User Name" required>
<div class="validation-error" *ngIf="UserName.invalid && UserName.touched">This Field is Required.</div>
</mat-form-field>
</div>
<div class="form-group col-md-6">
<mat-form-field class="example-full-width">
<input class="form-control" matInput placeholder="Height" name="Height" #Height="ngModel" [(ngModel)]="visitService.selectedVisit.height" placeholder="Height"
required>
<div class="validation-error" *ngIf="Height.invalid && Height.touched">This Field is Required.</div>
</mat-form-field>
</div>
</div>
<div class="form-group">
<mat-form-field class="example-full-width">
<input class="form-control" matInput placeholder="Temperature" name="Temperature" #Temperature="ngModel" [(ngModel)]="visitService.selectedVisit.temperature" placeholder="Temperature">
</mat-form-field>
</div>
<div class="form-group">
<mat-form-field class="example-full-width">
<input class="form-control" matInput placeholder="Weight" name="Weight" #Weight="ngModel" [(ngModel)]="visitService.selectedVisit.weight" placeholder="Weight">
</mat-form-field>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<mat-form-field class="example-full-width">
<input class="form-control" matInput placeholder="Blood Pressure" name="BloodPressure" #BloodPressure="ngModel" [(ngModel)]="visitService.selectedVisit.bloodpressure" placeholder="Blood Pressure">
</mat-form-field>
</div>
<div class="form-group col-md-6">
<mat-form-field class="example-full-width">
<input class="form-control" matInput placeholder="Patient Note" name="PatientNote" #PatientNote="ngModel" [(ngModel)]="visitService.selectedVisit.patientnote" placeholder="Patient Note">
</mat-form-field>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<mat-form-field class="example-full-width">
<input class="form-control" matInput placeholder="Nurse Note" name="NurseNote" #NurseNote="ngModel" [(ngModel)]="visitService.selectedVisit.nursenote" placeholder="Nurse Note">
</mat-form-field>
</div>
<div class="form-group col-md-6">
<mat-form-field class="example-full-width">
<input class="form-control" matInput placeholder="Doctor Note" name="DoctorNote" #DoctorNote="ngModel" [(ngModel)]="visitService.selectedVisit.doctornote" placeholder="Doctor Note">
</mat-form-field>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-8">
<button [disabled]="!visitForm.valid" type="submit" class="btn btn-lg btn-block btn-info">
<i class="fa fa-floppy-o"></i> Submit</button>
</div>
<div class="form-group col-md-4">
<button type="button" class="btn btn-lg btn-block btn-secondary" (click)="resetForm(visitForm)">
<i class="fa fa-repeat"></i> Reset</button>
</div>
</div>
</form>
Anyone please refer that.Thank You
See if you are displaying the value in html table or like that then after submit you have to destroy the table .
and again Reinit the table then only it will display the current added value as well.
So You can do that or else call the onload function when submit function ends .
or if you have some other issue then let me know in details.

Get response data from axios in vue.js

I am trying to get the response data from my REST API and to display it in my vue.js application as follows:
var database = new Vue({
el: '#database',
data: {
databaseConfiguration: {
type: '',
url: '',
port: '',
username: '',
password: ''
},
errors: []
},
created: function () {
axios.get('/config/database')
.then(function (response) {
this.databaseConfiguration = response.data;
console.log(response.data);
})
.catch(function (error) {
this.errors.push(error);
console.log(error);
})
}
}
)
If I debug it, I see that the response is correctly fetched from the REST API. But unfortunately the data is not displayed on the html page.
The html code looks as follows:
<div id="database" class="panel panel-default panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Database Configuration</h3>
</div>
<div class="panel-body">
<form class="form-horizontal">
<div class="form-group">
<label for="inputType" class="col-sm-2 control-label">Type</label>
<div class="col-sm-10">
<input type="text" v-model="databaseConfiguration.type" class="form-control" id="inputType"
placeholder="Database type">
</div>
</div>
<div class="form-group">
<label for="inputUrl" class="col-sm-2 control-label">Url</label>
<div class="col-sm-10">
<input type="text" v-model="databaseConfiguration.url" class="form-control" id="inputUrl"
placeholder="Url">
</div>
</div>
<div class="form-group">
<label for="inputPort" class="col-sm-2 control-label">Port</label>
<div class="col-sm-10">
<input type="number" v-model="databaseConfiguration.port" class="form-control" id="inputPort"
placeholder="Port">
</div>
</div>
<div class="form-group">
<label for="inputUsername" class="col-sm-2 control-label">Username</label>
<div class="col-sm-10">
<input type="text" v-model="databaseConfiguration.username" class="form-control"
id="inputUsername" placeholder="Password">
</div>
</div>
<div class="form-group">
<label for="inputPassword" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10">
<input type="password" v-model="databaseConfiguration.password" class="form-control"
id="inputPassword" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Save</button>
</div>
</div>
</form>
</div>
</div>
All the code can be found here.
Your this is pointing to the wrong object in your callbacks. Try using an arrow function, a closure, or bind.
Here is an example using an arrow function.
axios.get('/config/database')
.then(response => {
this.databaseConfiguration = response.data;
console.log(response.data);
})
.catch(error =>{
this.errors.push(error);
console.log(error);
})
See How to access the correct this inside a callback.

Bootstrap radio button & check box not diplayed

<div class="form-group" id="q-row5">
<div class="row">
<div class="col-sm-5 has-feedback">
<label for="preferContact" class="control-label">Preferred Contact Method *:</label>
<div>
<input class="control-label" id="Phone call" name="preferedContact[]" type="checkbox" value="1">
<label for="Phone call">Phone call</label>
</div>
<div>
<input class="control-label" id="Text" name="preferedContact[]" type="checkbox" value="2">
<label for="Text">Text</label>
</div>
<div>
<input class="control-label" id="Email" name="preferedContact[]" type="checkbox" value="3">
<label for="Email">Email</label>
</div>
<div>
<input class="control-label" id="Any" name="preferedContact[]" type="checkbox" value="4">
<label for="Any">Any</label>
</div>
</div>
<div class="col-sm-7 has-feedback">
<label for="messageType" class="control-label">What type of message may we leave when we contact you? *:</label>
<div style="">
<input class="control-label" id="messageTypeValDiscreet" name="messageTypeVal" type="radio" value="1">
<label for="messageTypeValDiscreet">Discreet</label>
</div>
<div style="">
<input class="control-label" id="messageTypeValAny" name="messageTypeVal" type="radio" value="2">
<label for="messageTypeValAny">Any</label>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#enrollForm')
.formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok icon-success',
invalid: 'glyphicon glyphicon-remove icon-fail',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
messageTypeVal: {
row: '.col-sm-7',
validators: {
notEmpty: {
message: 'Message type is required'
}
}
},
'preferedContact[]': {
row: '.col-sm-5',
validators: {
choice: {
min: 1,
message: 'Please choose prefered contact atleast 1'
}
}
}
}
});
});
</script>
attached image
My question is for the last options in both checkbox & radio button the label only is diplayed, the radio button and the checkbox is not displayed in both. I have attached the image. Please let me know what is the issues in code. If i remove the validation it works else it not working properly.