How to validate dynamic input field in vue.js? - javascript

I am using vuelidate to validate input field, the input field is dynamic i.e the value in input field is filled dynamically with jsonData using v-model
What I am trying to do is
On blur I want to show error if there is any, but here when I type anything inside my input field it shows nothing
what I am doing:- my input field
<div v-for="data in displayProfileData" :key="data.email" >
<p>{{data}}</p>
<div class="row">
<div class="form-group col-xs-6 col-sm-6 col-md-6 col-lg-3">
<label for="phoneNo">Name</label>
<input v-model="data.businessname"
#blur="$v.form.name.$touch()"
type="text"
class="form-control" name="name"
id="name">
<div v-if="$v.form.name.$error" class="form-error">
<span v-if="!$v.form.name.required" class="text-danger">nameis required</span>
</div>
</div>
<p>{{$v}}</p>
</div>
</div>
I am displaying $v on UI to check but when I type in input field no changes is been detected
My script code :-
<script>
import { required,minLength } from 'vuelidate/lib/validators'
import axios from '../../services/base-api'
export default {
data (){
return{
form :{
name:''
},
displayProfileData:[]
}
},
validations: {
form: {
name:{required},
}
},
created(){
this.userId = localStorage.getItem('user-Id')
axios().post('/api/v1/Profile/getProfileData',this.userId)
.then(res=>{
console.log(res.data)
this.displayProfileData=res.data
})
.catch(err=>{
this.$toasted.error(err,{duration:2000})
})
}
}
</script>
My data from server is in format like this { "businessid": "8126815643", "businessname": "manish",}
Issue
Initially when page loads in input field it shows manish so when I change it to something else and focus out it shows error that name is required I don't what is going wrong
2:Dynamic Form- Check Here
please check this

According to vuelidate's documentation, you should make the following changes:
<div v-for="data in $v.displayProfileData.$each.$iter" :key="data.email">
...
<input v-model="data.businessname.$model"
#blur="data.businessname.$touch()"
type="text"
class="form-control"
name="name"
id="name"
>
<div v-if="data.businessname.$error" class="form-error">
<span v-if="!data.businessname.required" class="text-danger">name is required</span>
</div>
...
</div>
validations: {
displayProfileData: {
//required,
//minLength: minLength(1),
$each: {
businessname: { required }
}
}
}
Attach my codesandbox example link

Related

onChange Input field is not change in react js edit update operation

onChange Input field is not change in react js edit update operation. all value fetch using API php. but if click in input field and enter some word not editable so give any solution. may be this issue using map function. if it is possible without map function.
Full Code share plz scroll down the page
enter image description here
all code show onChange Input field is not change in react js edit update operation
import React,{useState, useEffect} from 'react';
import axios from 'axios';
import { useParams } from 'react-router-dom';
//import './App.css';
const EditUser=()=>{
//function Home() {
// const navigate = useNavigate();
const {id} = useParams();
console.log(id);
// console.log("jjjjjj");
// alert(id);
const[titlecourse,settitlecourse]=useState("");
const[listshow,setlistshow]=useState("");
console.log(titlecourse);
const [userdata,setData]=useState ([]);
useEffect(()=>{
fetch(`https://www.example.com/jasonfile/wherecond.php?cid=${id}`).then((result)=>{
result.json().then((resp)=>{
// console.warn("result",resp)
console.log(resp)
setData(resp.data);
})
})
},[])
console.log(userdata);
// show array
return (
<div className="container">
<h1>Edit User {userdata.titlecourse}</h1>
<form >
{
userdata.map((item)=>
<div>
<div class="row mb-3">
<label for="inputEmail3" class="col-sm-2 col-form-label">titlecourse </label>
<div class="col-sm-10">
<input type="text" class="form-control"
name = "titlecourse"
value={item.titlecourse}
//value={titlecourse}
//placeholder={item.titlecourse}
onChange={(e)=>{settitlecourse(e.target.value)}}
/>
</div>
</div>
<div class="row mb-3">
<label for="inputPassword3" class="col-sm-2 col-form-label">listshow</label>
<div class="col-sm-10">
<input type="text" class="form-control"
name = "listshow"
value={item.listshow}
onChange={(e)=>{setlistshow(e.target.value)}}
/>
</div>
</div>
</div>
)
}
<button type="submit" class="btn btn-primary">Sign in</button>
</form>
</div>
);
}
export default EditUser;
all code show onChange Input field is not change value in react js edit update operation
output show in image
enter image description here
In order to see a value change in the input fields, you need to set the value prop as the state variables.
<div class="col-sm-10">
<input type="text" class="form-control"
name = "titlecourse"
value={titlecourse}
onChange={(e)=>{settitlecourse(e.target.value)}}
/>
</div>

How do I send data from a WYSIWYG to a database (Vue.js)

I just started using the Vue2Editor with the intention to replace the many forms that I use to send text and image data to my Firebase database.
My problem is that I cannot get it to add the data entered in the editor.
When using forms, I would just attach an event handler to the form itself and make a function that allowed the transfer.
Example:
<form #submit.prevent="addText">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname" v-model="fname">
</form>
<button type="submit" variant="success">Save</button>
But when using the Vue2Editor, I do not get any form tags.
I just get a "vue-editor" tag. I tried adding the event handler inside this tag, but nothing happens.
I don't get any errors, but the data is not transferred to the database upon submitting it.
This is the code:
<template>
<div class="container">
<div class="text_editor">
<h2>Add new content</h2>
<vue-editor #submit.prevent="addText" v-model="textblock" />
<button type="submit" class="textblock_btn" variant="success">Save</button>
</div>
</div>
</template>
<script>
import db from '#/firebase/init'
import Vue from "vue";
import Vue2Editor from "vue2-editor";
Vue.use(Vue2Editor);
export default {
name: 'textblock',
data () {
return {
textblock: null
}
},
methods: {
addText(){
db.collection('textblock').add({
textblock: this.textblock
}).then(() => {
this.$router.push({ name: 'Index' })
}).catch(err => {
console.log(err)
})
}
}
}
</script>
You can still wrap the component in a form as the WYSIWYG editor's data is bound to the v-model property.
<form #submit.prevent="addText">
<div class="text_editor">
<h2>Add new content</h2>
<vue-editor v-model="textblock" />
<button type="submit" class="textblock_btn" variant="success">Save</button>
</div>
</form>
Within the addText method you now have this.textblock with the appropriate data on form submission.

What is the easiest way to make editForm in Angular?

In my database i have many users which has many recipes.
Every recipe has some properties and collection of ingredients.
Below is screenshot
Recipe with all properties
So when user display recipe to edit on page should appear (form) recipe with loaded current data. This is kind of working because i can see the data but i think it's no done good.
I have form which is working fine without array (ingredients). Could you tell me how i should add ingredients to my edit form?
I'd be grateful if you see at my code and give me feedback and hints what i should change.
export class RecipeEditComponent implements OnInit {
#ViewChild('editForm') editForm: NgForm;
recipe: IRecipe;
photos: IPhoto[] = [];
ingredients: IIngredient[] = [];
uploader: FileUploader;
hasBaseDropZoneOver = false;
baseUrl = environment.apiUrl;
currentMain: IPhoto;
constructor(private route: ActivatedRoute, private recipeService: RecipeService,
private toastr: ToastrService) { }
ngOnInit(): void {
this.loadRecipe();
}
loadRecipe() {
this.recipeService.getRecipe(this.route.snapshot.params.id).subscribe(recipe => {
this.recipe = recipe;
this.initializeUploader();
})
}
updateRecipe(id: number) {
this.recipeService.editRecipe(id, this.recipe).subscribe(next => {
this.toastr.success('Recipe updated successfully');
this.editForm.reset(this.recipe);
}, error => {
this.toastr.error(error);
});
}
}
HTML
<div class="container mt-4 border" *ngIf="recipe">
<form #editForm="ngForm" id="editForm" (ngSubmit)="updateRecipe(recipe.id)" >
<h5 class=" text-center mt-2">Recipe details:</h5>
<div class="form-group mt-3">
<label for="city">Name</label>
<input class="form-control" type="text" name="name" [(ngModel)]="recipe.name">
</div>
<div class="form-group">
<app-ingredient-editor [ingredients] = "recipe.ingredients"></app-ingredient-editor>
<div *ngFor="let ingredient of recipe.ingredients; let i = index">
<input class="form-control" type="text" name="{{ingredient.name}}" [(ngModel)]="ingredient.name">
<input class="form-control" type="text" name="{{ingredient.amount}}" [(ngModel)]="ingredient.amount">
</div>
</div>
<div class="form-group">
<br>
<p>Add recipes</p>
</div>
<h5 class=" text-center mt-4">Description</h5>
<angular-editor cols=100% rows="6" [placeholder]="'Your description'" [(ngModel)]="recipe.description" name="description"></angular-editor>
</form>
<button [disabled]="!editForm.dirty" form="editForm" class="btn btn-success btn-block mb-5 mt-5">Save changes</button>
</div>
For now it's look like:
Form on page
When i delete ingredient name while changing on the console i have following error:
recipe-edit.component.html:12 ERROR Error: If ngModel is used within a form tag, either the name attribute must be set or the form
control must be defined as 'standalone' in ngModelOptions.
Problem is that part of code:
<div *ngFor="let ingredient of recipe.ingredients; let i = index">
<input class="form-control" type="text" name="{{ingredient.name}}" [(ngModel)]="ingredient.name">
<input class="form-control" type="text" name="{{ingredient.amount}}" [(ngModel)]="ingredient.amount">
</div>
</div>
But i don't know how to make it working..
How to add add array to template-driven form?
In my case i need to display current ingredients and be able to edit them.
I have tried something like this :
<input class="form-control" type="text" name="ingredient[i].name" [(ngModel)]="ingredient[i].name">
<input class="form-control" type="text" name="ingredient[i].amount" [(ngModel)]="ingredient[i].amount">
But id doesn't work
The problem is that the property name on the form must be defined in order for angular to know which input to update. You're binding name to the same property that the editable model is set to which means the user can edit it and in fact delete it, which isn't good.
The solution is to change it to a unique value that doesn't change. This should work:
<div *ngFor="let ingredient of recipe.ingredients; let i = index">
<input class="form-control" type="text" name="name{{ingredient.id}}" [(ngModel)]="ingredient.name">
<input class="form-control" type="text" name="amount{{ingredient.id}}" [(ngModel)]="ingredient.amount">
</div>
</div>
Link to stackblitz showing it working: https://stackblitz.com/edit/angular-10-base-template-q243lw?file=src%2Fapp%2Fapp.component.html
Edit: fixed bug in original post and added link to stackblitz

Submitting a form after validating with jquery validator on a button not in form tag

I have been battling with what is wrong on this code since. It so happens that the form is not submitting on this button. The button is of type button and not in the form tag.
$("#step1Btn").click(function () {
var userForm = $("form[name='step1Form']");
if (userForm.valid()) {
userForm.submit(function () {
console.log('submitted o!')
$("#spin1").show();
$("form[name='step1Form'] > span").remove();
$('input[name="emailInput"]').prop('name', "id")
$('input[name="fullNameInput"]').prop('name', "full-name")
$('input[name="phoneInput"]').prop('name', "phone-number")
$.ajax({
type: 'POST',
url: "api/v1/user?" + $(this).serialize(),
success: (result) => {
localStorage.setItem('user', JSON.stringify(result))
localStorage.setItem('authToken', result.authToken);
$("form[name='step1Form'] > span").remove()
$('#step1, #step2').toggle();
$('#step1Title, #step2Title').toggle();
},
error: function (request, exception, errorThrown) {
$("form[name='step1Form'] > span").remove();
$("form[name='step1Form']").prepend('<span class=\'error\'><p>' + request.responseJSON.message + '</p></span>')
},
})
});
} else {
return false;
}
});
Below is the complete form
<div id="step1" class="col-12 col-md-6">
<form name="step1Form">
<div class="home-icon d-flex justify-content-center align-items-center flex-column">
<img src="images/new-icons/user.png" alt="User Registration logo" height="80" />
<p class="my-3">User Registration</p>
</div>
<div class="form-group">
<label for="fullNameInput">Contact full name</label>
<input name="fullNameInput" class="form-control custom-input" placeholder="First name Last name" id="fullNameInput">
</div>
<div class="form-group">
<label for="emailInput">Contact email address</label>
<input name="emailInput" type="email" placeholder="example#email.com" class="form-control custom-input" id="emailInput">
</div>
<div class="form-group">
<label for="confirmEmailInput">Confirm contact email address</label>
<input name="confirmEmailInput" type="email" placeholder="example#email.com" class="form-control custom-input"
id="confirmEmailInput">
</div>
<div class="form-group">
<label for="phone">Contact phone number</label>
<input name="phoneInput" placeholder="08012345678" class="form-control custom-input" id="phone">
</div>
</form>
<button type="button" class="btn red-btn user-btn custom-btn" id="step1Btn">Next<i id="spin1" class="fa fa-spinner fa-spin"></i></button>
</div>
So I would like to see where I went wrong. I am able to log and see output whenever i place a console.log in between the if(userForm.valid) and the userForm.submit().
But as soon as i place it in the userform.submit() I do not get any value back. Like, the form is totally not submitting. I dont know if its because of how I made my Ajax call.. Please Help
You're putting Ajax inside of a submit....
$("#step1Btn").click(function () {
....
if (userForm.valid()) {
userForm.submit(function () {
....
$.ajax({ ....
Which makes no sense since Ajax replaces the actual submit. By doing this you are effectively sending it through validation again; I can't see the .validate() method, but suspect that you are simply using the default option, which would be yet another regular submit... you're probably stuck in a loop going nowhere.
The best place for your Ajax would be inside the submitHandler of the .validate() method.
If your button is outside of the form, you capture the click and manually trigger a submit, which then lets the validation plugin take over the rest.
$("#step1Btn").click(function () { // click of external button
$("form[name='step1Form']").submit(); // trigger validation & submission
});
$("form[name='step1Form']").validate({ // initialize plugin
submitHandler: function(form) { // fires when valid
// YOUR AJAX GOES INSIDE HERE
return false;
},
// other options, rules, etc.
});
Read the documentation for the submitHandler.

jquery form validation with submit button

i'm on my web site project and it seems that my jquery function doesn't work
.i have to validate this:if the user enters <<nom de famille du pere>>,<<prenom du pere>> has to be entered too.This is my html code:
<div class="form-group">
<div class="col-md-6">
<label class="col-md-4 control-label" for="father">Nom de famille du père </label>
<input id="father" name="father" type="text" class="form-control input-md" >
</div>
</div><br/><br/><br/>
<div class="form-group">
<div class="col-md-6">
<label class="col-md-4 control-label" for="ffather">Prénom du père</label>
<input id="ffather" name="ffather" type="text" class="form-control input-md">
</div>
</div><br/><br/><br/>
and this is my jquery function :
$(document).ready(function() {
$('#father').submit(function() {
if ($(this)).is(':empty')) {
$('#ffather').prop('required',false);
}
else{
$('#ffather').prop('required',true);
}} }
DEMO: http://jsfiddle.net/Lfnrrdfu/1/
you have a few mistakes in your code:
$('#father').on('keyup', function () {
if (!$(this).val()) {
$('#ffather').prop('required',false);
}
else{
$('#ffather').prop('required',true);
}
console.log($('#ffather').prop('required'));
});
You can't use submit event with an input, submit is for a form, you could use the form but then you have to prevent default then check the value of the input.
You are trying to set the attributes upon form submission, which is not the right way to do it. You should only check if the fields satisfy the requirements on submit. Defining the constrains should be on the markup. If you are not using any custom form validator, you can use HTML constrain validation. Examples can be found here
http://www.w3schools.com/js/js_validation.asp
Again, the jQuery submit event can ONLY be attached to form elements. Review here https://api.jquery.com/submit/

Categories