I have used syntax rule required_if from docs:
vee-validate required_if rule and it doesn't work.
Can someone point me to the right direction?
I need this simple required_if rule to work before I go further.
JSfiddle:
Vue.use(VeeValidate)
new Vue({
el: '#app',
data() {
return {
first: '',
last: '',
}
},
methods: {
onSubmit() {
this.$validator.validateAll()
.then(result => {
console.log(this)
alert(result)
})
}
}
})
#import url('https://unpkg.com/semantic-ui-css#2.2.9/semantic.css');
span.error {
color: #9F3A38;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/vee-validate#2.0.0-beta.25"></script>
<div id="app">
<form class="ui form" #submit.prevent="onSubmit">
<div class="field" :class="{error: errors.has('first')}">
<label>Name</label>
<input ref="firstName" type="text" name="first" placeholder="first" v-model="first">
<span class="error" v-if="errors.has('first')">{{errors.first('first')}}</span>
</div>
<div class="field" :class="{error: errors.has('last')}">
<label>Email</label>
<input type="text" name="last" placeholder="last" v-validate="'required_if:firstName,test'" v-model="last">
<span class="error" v-if="errors.has('last')">{{errors.first('last')}}</span>
</div>
<button type="submit" class="ui submit button">Submit</button>
</form>
</div>
#Randy Casburn pointed me right - thanks man!
The trouble was with versions. I got it working under this example:
my codesandbox
Hope it helps somebody ;-)
Related
this is the code I've implemented in vue.js
I was trying to add a new employee to the firebase database.
the code was working until I wrote the methods and initialized the data section
when I tried going back steps where the code was running it was still giving runtime error
<template>
<div class="container-fluid">
<center><h1>New Employee</h1></center>
<form #submit.prevent="adds" class="form">
<label>Enter Name</label>
<input type="text" class="form-control" v-modle="name">
<label>Enter Employee ID</label>
<input type="text" class="form-control" v-modle="emp_id">
<label>Enter Department</label>
<input type="text" class="form-control" v-modle="dep">
<label>Enter Position</label>
<input type="text" class="form-control" v-modle="position" >
<router-link to="/" class="btn btn-danger btn-lg">Cancel</router-link>
<button type="submit" class="btn btn-outline-success btn-lg">Submit</button>
</form>
</div>
</template>
<script>
import db from '../components/firebaseinit.js'
export default {
name:"newEmployee",
data(){
return{
name: null,
emp_id: null,
dep: null,
position: null
}
},
methods:{
adds(){
db.collection('employee').add({
emp_id: parseInt(this.emp_id),
name: this.name,
dep: this.dep,
position: this.position
}).then(this.router.push("/")).catch(err => console.log(err))
}
}
}
</script>
I found the problem with my code at line 42
then(this.router.push("/")).catch(err => console.log(err))
The right way to call router is by $ the code would be replaced by
then(() => this.$router.push("/")).catch(err => console.log(err))
This question already has answers here:
Validate dynamic field jquery
(2 answers)
Closed 2 years ago.
I have to clone the certain section of form and have to implement same validation rules defined previously.
As I researched on this issue, almost all them recommended to add new rules again in the newly generated elements. So, I had tried by adding new rule with following code
let $contactItem = $(".contact")
.first()
.clone()
.insertAfter($(".contact").last());
$contactItem.find("input").each(function(){
$(this).rules("add", {
required : true,
messages : { required : 'field is required.' }
});
});
But my bad luck, this technique did not solve my issue. So I am looking for another solution for it.
Some details on library I am using:
jQuery v1.9.1
jQuery Validation Plugin v1.17.0
$(document).ready(function() {
let $validator;
$("#btnAddNew")
.off("click")
.on("click", function() {
let $contactItem = $(".contact")
.first()
.clone()
.insertAfter($(".contact").last());
});
$validator = $("#contactForm").validate({
rules: {
firstName: {
required: true
},
lastName: {
required: true
}
},
messages: {
firstName: {
required: "* Required"
},
lastName: {
required: "* Required"
}
},
ignore: ":hidden, :disabled"
});
$("#btnSave")
.off("click")
.on("click", function() {
if ($validator.form()) {
console.log("ok");
}
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.19.2/dist/jquery.validate.js"></script>
<div class="container">
<form id="contactForm">
<div class="contact">
<h5 class="card-title">Contact Info</h5>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">First Name</label>
<input type="text" class="form-control" name="firstName" placeholder="Your First Name">
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">Last Name</label>
<input type="text" class="form-control" name="lastName" placeholder="Your Last Name">
</div>
</div>
</div>
<button type="button" id="btnAddNew" class="btn btn-primary">Add Next</button>
<button type="button" id="btnSave" class="btn btn-primary">Save</button>
</form>
</div>
Just adding required to the elements is probably the simplest solution and modify the default message.
I've also commented out an approach for setting class rules.
Note you also need to modify the names in order for them to be unique. I've used very simple incremental logic , modify if you will be adding and removing
$.extend($.validator.messages, {
required: "* required."
})
// Alternate using class rules
/*jQuery.validator.addClassRules("name-field", {
required: true
});*/
$(document).ready(function() {
let $validator;
$("#btnAddNew")
.off("click")
.on("click", function() {
let $contact = $(".contact");
let $contactItem = $contact
.first()
.clone()
.insertAfter($(".contact").last());
// increment input names
$contactItem.find('input').attr('name', function(_, curr) {
return curr + $contact.length
});
});
$validator = $("#contactForm").validate();
$("#btnSave")
.off("click")
.on("click", function() {
if ($validator.form()) {
console.log("ok");
}
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.19.2/dist/jquery.validate.js"></script>
<div class="container">
<form id="contactForm">
<div class="contact">
<h5 class="card-title">Contact Info</h5>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">First Name</label>
<input type="text" class="form-control name-field" name="firstName" placeholder="Your First Name" required>
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">Last Name</label>
<input type="text" class="form-control name-field" name="lastName" placeholder="Your Last Name" required>
</div>
</div>
</div>
<button type="button" id="btnAddNew" class="btn btn-primary">Add Next</button>
<button type="button" id="btnSave" class="btn btn-primary">Save</button>
</form>
</div>
First of all I would like to apologize if the answer to my question is obvious, however since I'm still pretty new to Vue.js, I'm getting really stuck here and I need help.
I got an authentication system and if the user wants to register without putting in an username, I would like to show an bootstrap alert. The code looks like this right now:
<template>
<div class="container">
<div class="row">
<div class="col-md-6 mt-5 mx-auto">
<form v-on:submit.prevent="register">
<h1 class="h3 mb-3 font-weight-normal">Register</h1>
<div class="form-group">
<label for="username">Username</label>
<input
type="text"
v-model="username"
class="form-control"
name="username"
placeholder="Please choose your username"
>
</div>
<div class="form-group">
<label for="email">Email Address</label>
<input
type="email"
v-model="email"
class="form-control"
name="email"
placeholder="Please enter your email address"
>
</div>
<div class="form-group">
<label for="password">Password</label>
<input
type="password"
v-model="password"
class="form-control"
name="password"
placeholder="Please choose your password"
>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Register</button>
</form>
<div>
<b-alert variant="success" show>Example alert</b-alert>
</div>
<div>
<b-alert variant="danger" :show="showAlert">Example Alert!</b-alert>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from "axios";
import router from "../router";
export default {
data() {
return {
username: "",
email: "",
password: "",
showAlert: false };
},
methods: {
register() {
axios
.post("/user/register", {
username: this.username,
email: this.email,
password: this.password
})
.then(res => {
if (!res.data.username) {
// show an alert, I would like to do something similar to "showAlert = true;"
} else {
// redirect to login
}
})
.catch(err => {
console.log(err);
});
}
}
};
</script>
<style scoped>
#import "../assets/css/reglog.css";
#import "../assets/css/modal.css";
</style>
However I'm not sure how to access the showAlert variable neither how to change its value in the if-statement. The only thing that I know here is that if I change the showAlert manually in the code (line 9 counting from the script tag) from false to true, the page does react and shows the alert when wanted.
I'm sorry if you need more information or if something is unclear, I'm a bit tired and stuck with this for some hours, not gonna lie.
You can access showAlert variable following: this.showAlert = true
.then(res => {
if (!res.data.username) {
this.showAlert = true; // update showAlert
} else {
// redirect to login
}
})
I'm a rookie on vue.js and I'm trying to extend some tutorials a completed.
Been fighting with this three hours now and I'm frustrated. FYI, I'm using firebase but I'm not sure it really matters here.
So, I have a CRUD app for listing movies (I told you it was basic!).
There is a form at the top of the page where you can add movies, and a table below it, where the new registries are listed. This works well.
I added Edit and Delete buttons to each row on the table. The delete function works. But the Edit function is the problem.
I'd like to use v-if on the initial form, to trigger different methods (save, edit) and show different buttons (Add, Save, Cancel).
I'm not sure how to access the objects to do this, I tried a couple of things and the v-if says the object is not defined.
thank you for reading, please ask anything you need.
import './firebase' // this has my credententials and initializeApp
import Vue from 'vue'
import App from './App'
import VueFire from 'vuefire'
Vue.use(VueFire)
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
template: '<App/>',
components: { App }
})
<template>
<div id="app" class="container">
<div class="page-header">
<h1>Vue Movies</h1>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h3>Add Movie</h3>
</div>
<div class="panel-body">
<div v-if="!isEditing">
<form id="form" class="form-inline" v-on:submit.prevent="addMovie">
<div class="form-group">
<label for="movieTitle">Title:</label>
<input type="text" id="movieTitle" class="form-control" v-model="newMovie.title">
</div>
<div class="form-group">
<label for="movieDirector">Director:</label>
<input type="text" id="movieDirector" class="form-control" v-model="newMovie.director">
</div>
<div class="form-group">
<label for="movieUrl">URL:</label>
<input type="text" id="movieUrl" class="form-control" v-model="newMovie.url">
</div>
<input type="submit" class="btn btn-primary" value="Add Movie">
</form>
</div>
<div v-else>
<form id="form" class="form-inline" v-on:submit.prevent="saveEdit(movie)">
<div class="form-group">
<label for="movieTitle">Title:</label>
<input type="text" id="movieTitle" class="form-control" v-model="movie.title">
</div>
<div class="form-group">
<label for="movieDirector">Director:</label>
<input type="text" id="movieDirector" class="form-control" v-model="movie.director">
</div>
<div class="form-group">
<label for="movieUrl">URL:</label>
<input type="text" id="movieUrl" class="form-control" v-model="movie.url">
</div>
<input type="submit" class="btn btn-primary" value="Save">
<button v-on:click="cancelEdit(movie['.key'])">Cancel</button>
</form>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h3>Movies List</h3>
</div>
<div class="panel-body">
<table class="table table-stripped">
<thead>
<tr>
<th>Title</th>
<th>director</th>
</tr>
</thead>
<tbody>
<tr v-for="movie in movies">
<td>
<a v-bind:href="movie.url" v-bind:key="movie['.key']" target="_blank">{{movie.title}}</a>
</td>
<td>
{{movie.director}}
</td>
<td>
<button v-on:click="editMovie(movie)">Edit</button>
</td>
<td>
<button v-on:click="removeMovie(movie)">Remove</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</template>
<script>
import { moviesRef } from './firebase'
export default {
name: 'app',
firebase: {
movies: moviesRef
},
data () {
return {
isEditing: false, // maybe this helps?
newMovie: {
title: '',
director: '',
url: 'http://',
edit: false // or maybe this??
}
}
},
methods: {
addMovie: function() {
moviesRef.push( this.newMovie )
this.newMovie.title = '',
this.newMovie.director = '',
this.newMovie.url = 'http://'
this.newMovie.edit = false
},
editMovie: function (movie){
moviesRef.child(movie['.key']).update({ edit:true }); // can't access this one with v-if, not sure why
//this.newMovie = movie;
},
removeMovie: function (movie) {
moviesRef.child(movie['.key']).remove()
},
cancelEdit(key){
moviesRef.child(key).update({ edit:false })
},
saveEdit(movie){
const key = movie['key'];
moviesRef.child(key).set({
title : movie.title,
director : movie.director,
url : movie.url,
edit : movie.edit
})
}
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
You should change the isEditing to true when the Edit button clicked, and you should define the data movie.
editMovie: function (movie){
...
this.movie = Vue.util.extend({}, movie); // deep clone to prevent modify the original object
this.isEditing = true;
},
As suggested in the comments (by Ben), I added the movie declaration to the initial data object. So now it looks like this:
data () {
return {
isEditing: false,
newMovie: {
title: '',
director: '',
url: 'http://',
edit: false
},
movie: {
edit: false
}
}
},
Now v-if works just fine, like this:
<div v-if="!movie.edit">
"is Editing" was no longer necessary so I removed it.
$(document).ready(function () {
jQuery.validator.addMethod("insz", function (value, element) {
var insz = $('#txtINSZ').val()
var controle = parseInt(insz.substring(13, 15))
var getal = insz.substring(0, 2) + insz.substring(3, 5) + insz.substring(6, 8) + insz.substring(9, 12)
var rest = parseInt(getal) % 97
alert("we doin' this mun")
return 97 - rest == controle;
}, "* Amount must be greater than zero");
$('#form1').validate({
rules: {
txtINSZ: {
required: $('#cbInsz').prop('checked') == false,
insz: function () {
$('#cbInsz').prop('checked') == true;
}
}
},
showErrors: function (errorMap, errorList) {
this.defaultShowErrors();// to display the default error placement
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.js"></script>
<form method="post" action="#" id="form1" a="" novalidate="novalidate">
<div id="container">
<div class="container-fluid">
<div class="col-xs-12">
<div class="form-horizontal col-xs-4" id="divDimLeft">
<span id="lblTitleAlgemeen">Algemen Informatie</span>
<div class="checkbox" style="margin-left:20px;">
<span id="lblCheck">
<input type="checkbox" id="cbInsz" checked="">
INSZ nummer werknemer gekend?
</span>
</div>
<div class="form-group" id="divINSZ">
<span id="lblINSZ" class="required" for="txtINSZ" aria-required="true">INSZ-nummer gekend?</span>
<input name="ctl00$ContentPlaceHolder1$txtINSZ" type="text" maxlength="15" id="txtINSZ" class="form-control required form valid" oninput="autoInvullen()" aria-required="true" placeholder="__.__.__-___.__" aria-invalid="false" required=""><label id="txtINSZ-error" class="error" for="txtINSZ" style="display: none;"></label>
</div>
<div class="form-group">
<span id="lblNaam" class="required" for="txtNaam" aria-required="true">Naam</span>
<input name="ctl00$ContentPlaceHolder1$txtNaam" type="text" maxlength="40" id="txtNaam" class="form-control form requiredField error" aria-required="true" aria-invalid="true"><label id="txtNaam-error" class="error" for="txtNaam">Dit veld is verplicht.</label>
</div>
<div id="divButton" class="text-right" style="width: 87.5%">
<input type="submit" name="ctl00$ContentPlaceHolder1$btnSubmit" value="Volgende" id="btnSubmit" class="btn btn-primary col-xs-2" style="float: none; min-width:200px;">
</div>
</div>
</div>
</div>
</div>
</form>
I wanted to make a custom validator but for some reason it's not working at all. The required does work so there is no issue with finding the elements in my page. So is there someone who has any idea why it is not working?
Thans in advance, under here you find the code i'm using including the method I wrote and the start of the validate method.
You can't just insert a comparison operator all by itself as the parameter; you need a function that returns the value of this parameter, in this case a boolean from the comparison operator...
$('#form1').validate({
rules: {
txtINSZ: {
required: function() {
return $('#cbInsz').prop('checked') == false;
},
insz: function() {
return $('#cbInsz').prop('checked') == false;
}
....
Solved it, I just putted the rules out of the rules section. After the validation code I putted this:
$('#txtINSZ').rules("add", {
required:true,
insz:true
})
Works perfectly.
I also faced the same situation, but in my case below two steps worked.
use data-rule-insz="true" attribute on your HTML input element for which you want custom validation.
also add a name attribute as mentioned in the below example:-
<input id="customer" name="customer" data-rule-insz="true" required type="text" class="typeahead form-control" />