How to extract a <form> element from Vuetify's <v-form> component - vuetify.js

I have a Vuetify form with a ref, like this
<v-form ref="form" method="post" #submit.prevent="handleSubmit">
Onto it I attached a default-preventing submit handler whose method is as follows:
window.fetch(`${this.$store.state.apiServer}/some-url`, {
method: 'post',
body: new FormData(this.$refs.form)
}).then(response => {
// Do stuff with the response
}).catch(() => {
// HCF
});
The problem is new FormData() only accepts a pure HTML <form> element, while this.$refs.form is a VueComponent. Is there a way I can grab the <form> from inside a <v-form>?

You can get the form element using this.$refs.form.$el
Here is the working codepen: https://codepen.io/chansv/pen/OJJOXPd?editors=1010
<div id="app">
<v-app id="inspire">
<v-form
ref="form"
v-model="valid"
lazy-validation
>
<v-text-field
v-model="name"
:counter="10"
:rules="nameRules"
label="Name"
required
></v-text-field>
<v-text-field
v-model="email"
:rules="emailRules"
label="E-mail"
required
></v-text-field>
<v-btn type="submit" #click="formSubmit">submit</v-btn>
</v-form>
</v-app>
</div>
new Vue({
el: '#app',
vuetify: new Vuetify(),
data: () => ({
valid: true,
name: '',
nameRules: [
v => !!v || 'Name is required',
v => (v && v.length <= 10) || 'Name must be less than 10 characters',
],
email: '',
emailRules: [
v => !!v || 'E-mail is required',
v => /.+#.+\..+/.test(v) || 'E-mail must be valid',
],
}),
methods: {
formSubmit() {
console.log(this.$refs.form.$el);
}
},
})

Related

Is there any option to have one common vuetify rule for two text fields

I have to fill either text-field-1 or text-field-2 or both In a form and I should be able to proceed with save
I tried having a flag variable but I that results in clicking on text-field-1 or text-field-2 to activate the save button
You can use computed property according to your need here is the basic example
new Vue({
el: '#app',
vuetify: new Vuetify(),
data: () => ({
valid: true,
firstName: '',
lastName: '',
nameRule: [
v => !!v || 'Name is required',
v => (v && v.length <= 10) || 'Name must be less than 10 characters',
],
}),
computed: {
nameRules () {
if(this.firstName.length == 0 && this.lastName.length == 0){
return this.nameRule;
}
if(this.firstName.length > 0 || this.lastName.length > 0 ){
return [];
}
},
},
methods: {
validate () {
this.$refs.form.validate()
},
reset () {
this.$refs.form.reset()
},
resetValidation () {
this.$refs.form.resetValidation()
},
},
})
<link href="https://cdn.jsdelivr.net/npm/vuetify#2.x/dist/vuetify.min.css" rel="stylesheet">
<div id="app">
<v-app id="inspire">
<v-form
ref="form"
v-model="valid"
lazy-validation
>
<v-text-field
v-model="firstName"
:counter="10"
:rules="nameRules"
label="First name"
></v-text-field>
<v-text-field
v-model="lastName"
:counter="10"
:rules="nameRules"
label="Last name"
></v-text-field>
<v-btn
:disabled="!valid"
color="success"
class="mr-4"
#click="validate"
>
Validate
</v-btn>
<v-btn
color="error"
class="mr-4"
#click="reset"
>
Reset Form
</v-btn>
<v-btn
color="warning"
#click="resetValidation"
>
Reset Validation
</v-btn>
</v-form>
</v-app>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue#2.x/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify#2.x/dist/vuetify.js"></script>

Cannot save multiple Image using Form Data

First of all this is the error that I get.
This is my first time working with Multiple Image with other Inputs.
as you can see in my FormData Headers the picture File is an Empty Array.
But inside the console it returns a file.
my question for this one that is this good? because the picture that I'm sending is a PNG one but it only says FILE.
This is my Vue Code.
<q-dialog
v-model="uploadForm"
transition-show="slide-up"
transition-hide="slide-down"
persistent
>
<q-card style="width: 700px; max-width: 50vw;">
<q-card-section>
<div class="text-h6">Add Product</div>
</q-card-section>
<div class="q-pa-md">
<form
action="http://127.0.0.1:8000/api/createProduct"
class="q-gutter-md"
method="POST"
enctype="multipart/form-data"
>
<q-input outlined label="Product name" v-model="data.productName" />
<q-input
multiple="multiple"
outlined
type="file"
accept="image/png,jpg/jpeg"
#change="onFilePicked"
ref="file"
>
<template v-slot:prepend>
<q-icon name="attach_file" />
</template>
</q-input>
<div>
<div class="image-category">
<div v-for="(image, key) in data.picture" :key="key">
<div class="image-item">
<img
class="grid"
:src="image.src"
width="300"
height="300"
/>
</div>
</div>
</div>
</div>
<q-input outlined label="Description" v-model="data.description" />
<q-input
prefix="₱ "
type="number"
outlined
label="Price"
v-model="data.price"
/>
<q-select
square
outlined
v-model="data.category_id"
:options="categories"
:option-value="'id'"
:option-label="'categoryName'"
label="Category"
/>
<div class="q-ma-md float-right">
<q-btn label="Submit" color="primary" #click="createProduct" />
<q-btn
label="Cancel"
color="primary"
flat
class="q-ml-sm"
#click="closeCreateModal"
/>
</div>
</form>
</div> </q-card
></q-dialog>
My returning Data()
data: {
picture: [],
productName: "Grizzly Bear",
description: "Machaba.",
price: "260000",
category_id: []
},
my #Change in accepting multiple Images.
onFilePicked(e) {
let selectedFiles = e.target.files;
for (let i = 0; i < selectedFiles.length; i++) {
let img = {
src: URL.createObjectURL(selectedFiles[i]),
file: selectedFiles[i]
};
this.data.picture.push(img);
console.log(this.data.picture, "inside");
}
console.log(this.data.picture, "outside");
},
My CreatingProduct method.
createProduct() {
let t = this.data;
if (
t.picture == "" ||
t.productName.trim() == "" ||
t.description.trim() == "" ||
t.price == "" ||
t.categories == ""
) {
this.uploadForm = false;
this.$q
.dialog({
title: "Incomplete Details",
message: "Please fill up all the fields in the Product",
persistent: true,
color: "negative"
})
.onOk(() => {
this.uploadForm = true;
});
} else {
let formData = new FormData();
const picture = JSON.stringify(this.data.picture); // returns [object, object] so I needed to do
//this.
const category_id = JSON.stringify(this.data.category_id);
formData.append("picture", picture);
formData.append("productName", this.data.productName);
formData.append("description", this.data.description);
formData.append("price", this.data.price);
formData.append("category_id", category_id);
let config = {
headers: {
"Content-Type": "multipart/form-data"
}
};
this.$axios
.post("http://127.0.0.1:8000/api/createProduct", formData, config)
.then(response => {
this.products.unshift(response.data);
this.uploadForm = false;
(this.data = ""),
this.$q.notify({
icon: "info",
message: "Product Added Successfully",
color: "positive"
});
})
.catch(() => {
this.$q.notify({
color: "negative",
position: "top",
message: "Unable to save Product",
icon: "report_problem"
});
});
}
}},
my Backend in laravel
public function createProduct(Request $request)
{
$this->validate($request,[
'productName' => 'required',
'description' => 'required',
'picture' => 'required|image|mimes:jpg,png,jpeg|max:2048',
'price' => 'required',
'category_id' => 'required'
]);
$product = new Product($request->input());
if($request->hasFile('picture')){
foreach($request->file('picture') as $file){
$name = $file->getClientOriginalName();
$file->move(public_path().'/uploads/',$name);
$product->picture = $name;
}
}
$product->save();
return response()->json($product);
}
Can anyone explain to me what is wrong? I made my research and it doesn't work. and also how do you edit a multiple Image? How would you select a specific image in the Index to make that one being edit.
this is my first time working with Quasar + Laravel in creating a Product with Multiple Image.
I think you are doing some things wrong, if you use a framework try to use it as it was intended either the validations or components they have, I detail an example
new Vue({
el: '#q-app',
data: function() {
return {
uploadForm: true,
data: {
picture: [],
productName: "Grizzly Bear",
description: "Machaba.",
price: "260000",
category_id: null
},
categories: [
{ id: 1, categoryName: 'categoria 1' }
]
}
},
methods: {
createProduct() {
this.$q.loading.show()
let formData = new FormData()
formData.append("picture", this.data.picture);
formData.append("productName", this.data.productName);
formData.append("description", this.data.description);
formData.append("price", this.data.price);
formData.append("category_id", this.data.category_id.id);
axios.post('http://localhost:8000/', formData, {
'headers': {
'Content-Type': 'multipart/form-data;'
}
}).then((response) => {
alert(response)
}).catch(error => {
if (error) {
console.log('error', error)
}
}).finally(() => {
this.$q.loading.hide()
})
},
closeCreateModal() {
alert('close')
},
}
})
<link rel="stylesheet"
type="text/css"
href="https://cdn.jsdelivr.net/npm/#quasar/extras/material-icons/material-icons.css">
<link rel="stylesheet"
type="text/css"
href="https://cdn.jsdelivr.net/npm/quasar/dist/quasar.min.css">
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://cdn.jsdelivr.net/npm/quasar/dist/quasar.umd.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="q-app">
<q-dialog v-model="uploadForm"
transition-show="slide-up"
transition-hide="slide-down"
persistent>
<q-card style="width: 700px; max-width: 50vw;">
<q-card-section>
<div class="text-h6">Add Product</div>
</q-card-section>
<q-card-section class="q-pt-none">
<div class="q-pa-md">
<q-form #submit="createProduct"
class="q-gutter-md">
<q-input outlined
label="Product name"
v-model="data.productName"
:rules="[val => !!val || 'Field is required']"></q-input>
<q-file multiple outlined v-model="data.picture" label="Outlined" accept="image/png,jpg/jpeg"
:rules="[val => !!val || 'Field is required']">
<template v-slot:prepend>
<q-icon name="attach_file" ></q-icon>
</template>
</q-file>
<q-input outlined
label="Description"
v-model="data.description"
:rules="[val => !!val || 'Field is required']"></q-input>
<q-input prefix="₱ "
type="number"
outlined
label="Price"
v-model="data.price"
:rules="[val => !!val || 'Field is required']"></q-input>
<q-select square
outlined
v-model="data.category_id"
:options="categories"
option-value="id"
option-label="categoryName"
label="Category"
:rules="[val => !!val || 'Field is required']"
></q-select>
<div>
<q-btn label="Submit"
color="primary"
type="submit"></q-btn>
<q-btn label="Cancel"
#click="closeCreateModal"
flat class="q-ml-sm"></q-btn>
</div>
</q-form>
</div>
</q-card-section>
</q-card>
</q-dialog>
</div>
if you see the log the "picture" attribute has an array of Object File
I leave the backend processing (laravel) at your discretion
I think it would be easier if you share a link with your problem for future reference
https://jsfiddle.net/idkc/L8xn0puq/52/

Vuetify v-combobox validations not working

I have a Vuetify(v. 1.9.0) v-combobox with validation that at least one item should be selected from the menu. For some reason the validation is not triggered and there are no errors in the console.
<v-combobox
multiple
item-text="name"
item-value="id"
:items="items"
:rules="[rules.required]"
></v-combobox>
<script>
export default {
data: () => ({
rules: {
required: value =>
!!value || "Required."
}
})
}
</script>
What am I missing?
Try this example:
<template>
<v-app>
<v-content>
<v-form ref="form">
<div>
<v-combobox
multiple
item-text="name"
item-value="id"
:items="items"
:rules="[required]"
v-model="selected"
/>
selected = {{ selected }}
</div>
<div>
<v-btn #click="$refs.form.validate()">Validate</v-btn>
</div>
</v-form>
</v-content>
</v-app>
</template>
<script>
export default {
name: 'app',
data: () => ({
selected: null,
items: [
{ id: 1, name: 'Option 1' },
{ id: 2, name: 'Option 2' },
{ id: 3, name: 'Option 3' },
],
}),
methods: {
required(value) {
if (value instanceof Array && value.length == 0) {
return 'Required.';
}
return !!value || 'Required.';
},
},
};
</script>

How to add password matching validation in vuetify?

I am trying to create a profile form which have two fields
password and rePassword. basically, Both of them should be the same.
I tried using different codes found on the web and different approaches. Some of them worked but. It did'nt actually fit in with the code.
Here is the piece of code:
Profile.vue:
<v-layout>
<v-flex xs12 sm6>
<v-text-field
v-model="password"
:append-icon="show ? 'visibility' : 'visibility_off'"
:rules="[rules.required, rules.min]"
:type="show ? 'text' : 'password'"
name="password"
label="Enter Password"
hint="At least 8 characters"
counter
#click:append="show = !show"
></v-text-field>
</v-flex>
<v-flex xs12 sm6>
<v-text-field
v-model="rePassword"
:append-icon="show1 ? 'visibility' : 'visibility_off'"
:rules="[rules.required, rules.min]"
:type="show1 ? 'text' : 'password'"
name="input-10-1"
label="Re-enter Password"
hint="At least 8 characters"
counter
#click:append="show1 = !show1"
></v-text-field>
</v-flex>
</v-layout>
This is how the script looks like:
Profile.vue (script):
data() {
return {
show: false,
show1: false,
password: 'Password',
rePassword: 'Password',
rules: {
required: value => !!value || 'Required.',
min: v => v.length >= 8 || 'Min 8 characters',
emailMatch: () => ('The email and password you entered don\'t match')
},
emailRules: [
v => !!v || 'E-mail is required',
v => /.+#.+/.test(v) || 'E-mail must be valid'
],
date: new Date().toISOString().substr(0, 10),
menu: false,
items: ['male', 'female'],
address: '',
title: "Image Upload",
dialog: false,
imageName: '',
imageUrl: '',
imageFile: ''
}
},
methods: {
pickFile() {
this.$refs.image.click()
},
onFilePicked(e) {
const files = e.target.files
if(files[0] !== undefined) {
this.imageName = files[0].name
if(this.imageName.lastIndexOf('.') <= 0) {
return
}
const fr = new FileReader ()
fr.readAsDataURL(files[0])
fr.addEventListener('load', () => {
this.imageUrl = fr.result
this.imageFile = files[0] // this is an image file that can be sent to server...
})
} else {
this.imageName = ''
this.imageFile = ''
this.imageUrl = ''
}
},
}
,
validate() {
if (this.$refs.form.validate()) {
this.snackbar = true
}
},
reset() {
this.$refs.form.reset()
}
How do I add a password matching feature in the validation using vuetify.
Thanks
You can define custom rules:
computed: {
passwordConfirmationRule() {
return () => (this.password === this.rePassword) || 'Password must match'
}
}
and use it
<v-flex xs12 sm6>
<v-text-field
v-model="rePassword"
:append-icon="show1 ? 'visibility' : 'visibility_off'"
:rules="[rules.required, rules.min, passwordConfirmationRule]"
:type="show1 ? 'text' : 'password'"
name="input-10-1"
label="Re-enter Password"
hint="At least 8 characters"
counter
#click:append="show1 = !show1"
/>
</v-flex>
very easiest way is
using v-model (password and confirm_password), no need to use computation
Rule
:rules="[v => !!v || 'field is required']"
Or
:rules="[(password!="") || 'field is required']"
in password
<v-text-field label="Password*" v-model="password" type="password" required :rules="[v => !!v || 'field is required']"></v-text-field>
confirm password field
Rule
:rules="[(password === confirm_password) || 'Password must match']"
code:
<v-text-field label="Confirm Password*" v-model="confirm_password" type="password" required :rules="[(password === confirm_password) || 'Password must match']"></v-text-field>
VeeValidate is great for form validation but in my opinion is overkill for resolving this question when it can be achieved in Vuetify alone.
Following on from #ittus answer, you need to remove the arrow function in passwordConfirmationRule to access this:
return this.password === this.rePassword || "Password must match";
See this codesandbox working example (also now using Vuetify 2.x)
Very simply using Vee-validate:
<div id="app">
<v-app id="inspire">
<form>
<v-text-field
ref="password"
type="password"
v-model="pass"
v-validate="'required'"
:error-messages="errors.collect('pass')"
label="Pass"
data-vv-name="pass"
required
></v-text-field>
<v-text-field
v-model="pass2"
type="password"
v-validate="'required|confirmed:password'"
:error-messages="errors.collect('pass2')"
label="Pass 2"
data-vv-name="pass"
required
></v-text-field>
<v-btn #click="submit">submit</v-btn>
<v-btn #click="clear">clear</v-btn>
</form>
</v-app>
</div>
Vue.use(VeeValidate)
new Vue({
el: '#app',
$_veeValidate: {
validator: 'new'
},
data: () => ({
pass: '',
pass2: "",
}),
methods: {
submit () {
this.$validator.validateAll()
.then(result => {
console.log(result)
})
},
clear () {
this.pass = ''
this.pass2 = ''
}
}
})
Remember to install vee-validate first and restart your local-server.
link to codepen
link to docs
This works right for me!
// template
<v-text-field v-model="password" label="password"></v-text-field>
<v-text-field v-model="confirmPassword" :rules="confirmPasswordRules" label="confirmPassword"></v-text-field>
// script
computed: {
confirmPasswordRules() {
const rules = [(this.password === this.confirmPassword) || "Password must match."];
return rules;
},
}
This is not a clean solution definitely, but works fine.
<v-text-field
type="password"
v-model="password"
:rules="passwordRules"
required
></v-text-field>
<v-text-field
type="password"
v-model="passwordConfirm"
:rules="passwordConfirmRules"
required
></v-text-field>
let globalPassword = "";
watch: {
password() {
globalPassword = this.password;
},
},
passwordConfirmRules = [
(v) => v === globalPassword || "Password must match",
];

Vuetify v-text-field : how to set success status automatically from rules

When I manually set the success prop on v-text-field, it turns green.
Is there anyway to get it to turn green automatically from just passing the rules?
<v-form ref="form" v-model="valid" lazy-validation>
<v-text-field
v-model="name"
:rules="nameRules"
:counter="10"
label="Name"
required
></v-text-field>
</v-form>
new Vue({
el: '#app',
data: () => ({
valid: true,
name: '',
nameRules: [
v => !!v || 'Name is required',
v => (v && v.length <= 10) || 'Name must be less than 10 characters'
]
})
https://codepen.io/damianhelme/pen/OaepbX

Resources