I have one problem. I have to make my error messages display outside of form, but I have no idea how to make it, because my javascript is displaying messages, when the error message class is inside in the form. is it possible to make it outside of form?
This is picture, how it looks. In this example I want to display errors below the red button.1
<form class="ui form" id="companyForm" style="margin-top:1em">
<div class="two fields">
<div class="field">
<input type="text" name="companyName" placeholder="Company name">
</div>
<div class="field">
<input type="text" name="companyCode" placeholder="Company code">
</div>
</div>
<div class="field">
<input type="text" name="companyAddress" placeholder="Company address">
</div>
<div class="ui error message"></div>
</form>
<div class="ui bottom attached red button" onclick="submitForm(this);">
<p><b>Place order</b> <i class="large shop icon"></i></p>
</div>
<div class="ui error message"></div>
function submitForm(){
var formValidationRules2 =
{
companyName: {
identifier: 'companyName',
rules: [
{
type : 'minLength[2]',
prompt : 'Your Company name must be at least {ruleValue} characters'
}
]
},
companyCode: {
identifier: 'companyCode',
rules: [
{
type : 'minLength[4]',
prompt : 'Your Company code must be at least {ruleValue} characters'
}
]
},
companyAddress: {
identifier: 'companyAddress',
rules: [
{
type : 'minLength[10]',
prompt : 'Your Company address must be at least {ruleValue} characters'
}
]
}
}
$("#companyForm").form(formValidationRules2);
$("#companyForm").form('validate form');
if($("#companyForm").form('is valid')){
joooo();
}
}
Related
I have been working with Vue for 24 hours now, so forgive the ignorance. I have searched around and I'm getting close, but I'm sure it's my lack of understanding and basic principles.
I have a modal that opens when a button is clicked. This modal displays a form with an email input. I managed to get the modal working, but nothing happens when I type in an incorrect email.
Here's my code for the component:
<template>
<div>
<!-- Aside -->
<aside class="aside">
<button class="aside__btn button" #click="showModal = true">
Send Me The Tips
</button>
</aside>
<!-- Modal -->
<div class="modal" v-if="showModal">
<div class="modal-container">
<p class="modal__steps">Step 1 of 2</p>
<div class="relative">
<hr class="modal__divider" />
</div>
<div class="modal__heading-container">
<p class="modal__heading">Email Your Eail To Get <span class="modal__heading-span">Free</span>
</p>
<p class="modal__heading">iPhone Photography Email Tips:</p>
</div>
<form>
<input for="email" type="email" placeholder="Please enter your email here" required v-model="email">
<span class="floating-placeholder" v-if="msg.email">{{msg.email}}</span>
<!-- <span class="floating-placeholder">Please enter your email here</span> -->
<button class="modal__button button">Send Me The Tips</button>
</form>
</div>
</div>
</div>
</template>
<script>
export default ({
data () {
return {
showModal: false,
email: '',
msg: [],
}
},
watch: {
email(value) {
// binding this to the data value in the email input
this.email = value;
this.validateEmail(value);
}
},
methods: {
validateEmail(value){
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(value))
{
this.msg['email'] = '';
} else{
this.msg['email'] = 'Please enter a valid email address';
}
}
}
})
</script>
I'm using Laravel if that's of importance.
I would delete the watch and add an event listener on blur like so:
<input for="email" type="email" placeholder="Please enter your email here" required v-model="email" #blur="validateEmail" >
and update the validateEmail method like so :
validateEmail() {
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(this.email)) {
this.msg['email'] = 'Please enter a valid email address';
} else {
this.msg['email'] = '';
}
}
You could also change the event listener to change #change if it serves your needs better.
You could also checkout Vuelidate which handles form validation. For example:
<template>
<div>
<input
class="rounded shadow-sm border border-warning"
v-model="form.email"
placeholder="E-mail"
#input="$v.form.email.$touch"
:state="$v.form.email.$dirty ? !$v.form.email.$error : null" />
</div>
</template>
<script>
import {required, email} from "vuelidate/lib/validators";
export default {
data() {
return {
form: {
email: null,
}
};
},
validations: {
form: {
email: {
required,
email
}
}
},
};
</script>
There are two buttons called ADD and REMOVE. If the user clicks on ADD it will add one more input field for FULL NAME. I am using validationText to display text as PLEASE ENTER MORE THAN 5 CHARACTERS for full name. If I ADD two fields and insert only two characters in second one then it displays validationText on both input fields as
Is there a way to display validationText message to the particular field which consists of less than 5 characters?
View
<div id="app">
<div class="work-experiences">
<div class="form-row" v-for="(minordatabase, index) in minorsDetail" :key="index">
<div class="col">
<br>
<label id="minorHeading">FULL NAME</label>
<input v-model="minordatabase.full_name" type="text" class="form-control" placeholder="FULL NAME" size="lg" #input="checkValidation"/>
<p v-show="!validationText" style="color:red;">
Please enter than 5 characters
</p>
</div>
</div>
</div>
<br>
<div class="form-group">
<button #click="addExperience" type="button" class="btn btn-info" style="margin-right:1.5%;">Add</button>
<button #click="removeExperience" type="button" class="btn btn-outline-info">Remove Last Field</button>
</div>
</div>
Script
new Vue({
el: "#app",
data: {
minorsDetail: [
{
full_name: "",
date_of_birth: "",
}
],
validationText: true
},
methods: {
checkValidation(){
console.log("SAN");
var minorsDetailLastElement = this.minorsDetail[this.minorsDetail.length-1].full_name.length;
console.log(minorsDetailLastElement);
if(minorsDetailLastElement > 2){
this.validationText = false;
}
if(minorsDetailLastElement > 5){
this.validationText = true;
}
},
addExperience(){
this.minorsDetail.push({
full_name: ''
})
},
removeExperience: function(todo){
var index = this.minorsDetail.indexOf(todo)
this.minorsDetail.splice(index, 1)
this.removeMinorFieldFunction();
},
}
})
Below is the code on JSFIDDLE
https://jsfiddle.net/ujjumaki/5mqp1bag/28/
You only have one validationText for all fields. So, if you set it for one field, it's going to show up in the other field too.
I recommend doing something like this instead to show the validation:
<p v-if="minordatabase.full_name.length > 2 && minordatabase.full_name.length < 5" style="color: red;">
Please enter more than 5 characters
</p>
I want to use the jquery plugin for validating my form with letters only in name section. such that when a user enters special characters or numbers it gives an error. Also i want to check the form validation as the users types the information i.e. realtime validation before submitting the form.
//jquery validation
// Wait for the DOM to be ready
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "registration"
$("form[name='book']").validate({
// Specify validation rules
rules: {
// The key name on the left side is the name attribute
// of an input field. Validation rules are defined
// on the right side
fname: {
required: true,
lettersonly: true
},
lname:{
required: true,
lettersonly: true
},
email: {
required: true,
// Specify that email should be validated
// by the built-in "email" rule
email: true
},
// Specify validation error messages
messages: {
fname: {
required:"Please enter your firstname",
lettersonly:"Letters allowed only"
},
lname: {
required:"Please enter your firstname",
lettersonly:"Letters allowed only"
},
email: "Please enter a valid email address"
},
// Make sure the form is submitted to the destination defined
// in the "action" attribute of the form when valid
submitHandler: function(form) {
form.submit();
}
});
});
<script src="design/bootstrap-3.3.7-dist/js/jquery.validate.js"></script>
<script src="design/bootstrap-3.3.7-dist/js/additional-methods.js"></script>
<form name="book" id="book" action="" method="post">
<div class="row form-group">
<div class="col-md-6 ">
<label class="" for="fname">First Name</label>
<input type="text" name="fname" id="fname" class="form-control" placeholder="First Name">
</div>
<div class="col-md-6">
<label class="" for="lname">Last Name</label>
<input type="text" name="lname" id="lname" class="form-control" placeholder="Last Name">
</div>
</div>
<div class="row form-group">
<div class="col-md-6 ">
<label class="" for="date">Date</label>
<input type="text" id="date" class="form-control datepicker px-2" placeholder="Date of visit">
</div>
<div class="col-md-6">
<label class="" for="email">Email</label>
<input type="email" name="email" id="email" class="form-control" placeholder="Email">
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<label class="" for="treatment">Service You Want</label>
<select name="treatment" id="treatment" class="form-control">
<option value="">Hair Cut</option>
<option value="">Hair Coloring</option>
<option value="">Perms and Curls</option>
<option value="">Hair Conditioning</option>
<option value="">Manicure</option>
<option value="">Pedicure</option>
<option value="">Nails Extension</option>
<option value="">Nail Design</option>
<option value="">Waxing Eyebrows</option>
<option value="">Waxing Hands/Legs</option>
<option value="">Full Face Waxing</option>
<option value="">Full Body/Body Parts Wax</option>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<label class="" for="note">Notes</label>
<textarea name="note" id="note" cols="30" rows="5" class="form-control" placeholder="Write your notes or questions here..."></textarea>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<center><input type="submit" value="Book Now" class="btn btn-primary btn-lg"></center>
</div>
</div>
</form>
I want to use the jquery plugin for validating my form with letters only in name section. such that when a user enters special characters or numbers it gives an error
var RegEx = /^[a-zA-Z\s]*$/;
if (RegEx.test($('#input').val())) {
}
else {
$('#input').val("");
}
});````
You have to wrap all the input elements in <form></form> and use jquery Validate plugin. Refer this link: http://jqueryvalidation.org/validate/ for detailed explanation
How about doing something like this?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<form id="form">
<label for="name">Name: </label>
<input type="text" name="name">
<div id="error"></div>
</form>
<script>
;(function($){
$.fn.extend({
donetyping: function(callback,timeout){
timeout = timeout || 1e3; // 1 second default timeout
var timeoutReference,
doneTyping = function(el){
if (!timeoutReference) return;
timeoutReference = null;
callback.call(el);
};
return this.each(function(i,el){
var $el = $(el);
// Chrome Fix (Use keyup over keypress to detect backspace)
// thank you #palerdot
$el.is(':input') && $el.on('keyup keypress paste',function(e){
// This catches the backspace button in chrome, but also prevents
// the event from triggering too preemptively. Without this line,
// using tab/shift+tab will make the focused element fire the callback.
if (e.type=='keyup' && e.keyCode!=8) return;
// Check if timeout has been set. If it has, "reset" the clock and
// start over again.
if (timeoutReference) clearTimeout(timeoutReference);
timeoutReference = setTimeout(function(){
// if we made it here, our timeout has elapsed. Fire the
// callback
doneTyping(el);
}, timeout);
}).on('blur',function(){
// If we can, fire the event since we're leaving the field
doneTyping(el);
});
});
}
});
})(jQuery);
function validate(value) {
var regex = /\d/g;
if (regex.test(value)) {
$('#error').text('Only text allowed!');
} else {
$('#error').empty();
}
}
$('input[name=name]').donetyping(function(e){
validate($(this).val());
});
</script>
</body>
</html>
Credits to this https://stackoverflow.com/a/14042239/9379378
//jquery validation booking page
// Wait for the DOM to be ready
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "registration"
$("form[name='book']").validate({
//on key up validation
onkeyup: function(element) {
$(element).valid();
},
// Specify validation rules
rules: {
// The key name on the left side is the name attribute
// of an input field. Validation rules are defined
// on the right side
fname: {
required: true,
lettersonly: true
},
lname:{
required: true,
lettersonly: true
},
email: {
required: true,
// Specify that email should be validated
// by the built-in "email" rule
email: true
},
password: {
required: true,
minlength: 5
}
},
// Specify validation error messages
messages: {
fname: {
required:"Please enter your firstname",
lettersonly:"Letters allowed only"
},
lname: {
required:"Please enter your lastname",
lettersonly:"Letters allowed only"
},
email: "Please enter a valid email address"
},
// Make sure the form is submitted to the destination defined
// in the "action" attribute of the form when valid
submitHandler: function(form) {
form.submit();
}
});
});
This question already exists:
jQuery show/hide form with jQuery validate plugin working on last shown div only
Closed 4 years ago.
I am trying to validate my form that is a jQuery show/hide form. jQuery validate plugin only validates my last input on the last div (input type file). I can currently upload an image and submit the form successfully with the remaining inputs empty.
Below is the third div and when i click post ad with no inputs filled in, "This field is required" is shown.
Below is the first div with no validation messages
Below is the second div with no validation messages
Here is my form:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Zootopia</title>
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
</head>
<body>
<form id="ad_form" method="post">
<div id="ad_form_section1">
<div class="form-group">
<label for="ad_title">Ad Title</label>
<input type="text" class="form-control stored" id="ad_title" placeholder="e.g. German Sheperd puppy - 4 months old" name="ad_title" required>
</div>
<div class="form-group">
<label for="description">Describe what you're offering</label>
<textarea class="form-control stored" id="description" rows="6" placeholder="e.g. Owner supervised visits, minimum 1hr bookings, play with my german sheperd puppy in my backyard" name="description" required></textarea>
</div>
<button type="button" id="ad_section2" class="btn btn-primary"> Next </button>
</div>
<div id="ad_form_section2">
<div class="form-group">
<label for="location"> Location</label>
<input type="text" id="location_ad" class="form-control stored" placeholder="location" name="location" required/>
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="text" id="price" class="form-control stored" name="price" placeholder="$0.00" required/>
</div>
<button type="button" id="back_section1" class="btn btn-primary"> Back </button>
<button type="button" id="ad_section3" class="btn btn-primary"> Next </button>
</div>
<div id="ad_form_section3">
<div>
<label> Select pet pictures</label>
<input type="file" name="multiple_files[]" id="multiple_files" multiple required/>
</div>
<button type="button" id="back_section2" class="btn btn-primary"> Back </button>
<input type="hidden" name="action_type" value="add" />
<input type="submit" id="ad_button" class="btn btn-primary" value="Post ad" />
</div>
</form>
Here is my JavaScript:
$(document).ready(function(){
$("#ad_section2").click(function(){
$("#ad_form_section1").hide();
$("#ad_form_section2").show();
});
$("#back_section1").click(function(){
$("#ad_form_section1").show();
$("#ad_form_section2").hide();
});
$("#ad_section3").click(function(){
$("#ad_form_section3").show();
$("#ad_form_section2").hide();
});
$("#back_section2").click(function(){
$("#ad_form_section2").show();
$("#ad_form_section3").hide();
});
$("#ad_form").validate({
rules:{
ad_title:{
required: true
},
description:{
required: true
},
location:{
required: true
}
},
messages:{
ad_title: {
required: "please enter an ad title"
},
description: {
required: "please enter a description"
},
location: {
required: "please enter a location"
}
},
submitHandler: function(form) {
var petID = $( "#pet_ad option:selected" ).val();
var addAdUrl = "../../controller/post_ad_process.php?petID=" + petID;
$(form).ajaxSubmit({
url:addAdUrl,
type:"post",
datatype: 'json',
success: function(result){
if(result.petAd == false){
alert("Pet ad already exists!");
}else{
alert("Ad posted!");
$('#image_table').hide();
}
},
error: function(error) {
alert("Error");
}
});
}
});
})
Here is my CSS:
#ad_form_section2,
#ad_form_section3{
display: none;
}
You need to add a condition before you show/hide next fields
if ( $('field-id').valid() ) {
// Code
}
For example:
$("#ad_section2").click(function(){
if ($('#ad_title').valid() && $('#description').valid()) {
$("#ad_form_section1").hide();
$("#ad_form_section2").show();
}
});
Also, don't forget to set character encoding to avoid characters range error, Add the following code just below <head> tag:
<meta charset="UTF-8">
Form Example:
$(document).ready(function(){
$("#ad_form").validate({
rules:{
ad_title:{
required: true,
minlength: 3, // set minimum title length
},
description:{
required: true,
minlength: 10,
},
location:{
required: true
}
},
messages:{
ad_title: {
required: "please enter an ad title",
minlength: "Your title must be more than 3 characters!",
},
description: {
required: "please enter a description",
minlength: "Your description must be at least 10 characters long",
},
location: {
required: "please enter a location"
}
},
submitHandler: function(form) {
var petID = $( "#pet_ad option:selected" ).val();
var addAdUrl = "../../controller/post_ad_process.php?petID=" + petID;
$(form).ajaxSubmit({
url:addAdUrl,
type:"post",
datatype: 'json',
success: function(result){
if(result.petAd == false){
alert("Pet ad already exists!");
}else{
alert("Ad posted!");
$('#image_table').hide();
}
},
error: function(error) {
alert("Error");
}
});
}
});
$("#ad_section2").click(function(){
// Check if valid before show/hide
if ($('#ad_title').valid() && $('#description').valid()) {
$("#ad_form_section1").hide();
$("#ad_form_section2").show();
}
});
$("#back_section1").click(function(){
$("#ad_form_section1").show();
$("#ad_form_section2").hide();
});
$("#ad_section3").click(function(){
// Check if valid before show/hide
if ($('#location_ad').valid()) {
$("#ad_form_section3").show();
$("#ad_form_section2").hide();
}
});
$("#back_section2").click(function(){
$("#ad_form_section2").show();
$("#ad_form_section3").hide();
});
});
#ad_form_section2,
#ad_form_section3 {
display: none;
}
label.error {
color: red;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<div class="container">
<form id="ad_form" method="post">
<div id="ad_form_section1">
<div class="form-group">
<label for="ad_title">Ad Title</label>
<input type="text" class="form-control stored" id="ad_title" placeholder="e.g. German Sheperd puppy - 4 months old" name="ad_title">
</div>
<div class="form-group">
<label for="description">Describe what you're offering</label>
<textarea class="form-control stored" id="description" rows="6" placeholder="e.g. Owner supervised visits, minimum 1hr bookings, play with my german sheperd puppy in my backyard" name="description" required></textarea>
</div>
<button type="button" id="ad_section2" class="btn btn-primary"> Next </button>
</div>
<div id="ad_form_section2">
<div class="form-group">
<label for="location"> Location</label>
<input type="text" id="location_ad" class="form-control stored" placeholder="location" name="location" required/>
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="text" id="price" class="form-control stored" name="price" placeholder="$0.00" required/>
</div>
<button type="button" id="back_section1" class="btn btn-primary"> Back </button>
<button type="button" id="ad_section3" class="btn btn-primary"> Next </button>
</div>
<div id="ad_form_section3">
<div>
<label> Select pet pictures</label>
<input type="file" name="multiple_files[]" id="multiple_files" multiple required/>
</div>
<button type="button" id="back_section2" class="btn btn-primary"> Back </button>
<input type="hidden" name="action_type" value="add" />
<input type="submit" id="ad_button" class="btn btn-primary" value="Post ad" />
</div>
</form>
</div>
More examples from documentation
By default the plugin is going to ignore any/all fields that are hidden. You have to set to the ignore option to "nothing".
$("#ad_form").validate({
ignore: [], // ignore nothing, validate everything
rules:{
ad_title:{ ....
If you're expecting validation when you show/hide sections of the form, that's not how it works. You're going to have to programmatically trigger validation on the relevant fields as you click back and forth. Use the .valid() method for this.
However, multi-step validation can quickly get tedious so you may have to re-think your entire approach. I personally like to enclose each section within its own set of <form></form> tags so I can control validation on each step separately.
Here's one example:
https://stackoverflow.com/a/20481497/594235
I am using the Jquery validation plugin to validate the Dynamic Form.I am getting error messages as wanted but the main problem is whether the required fields are empty or not whatever the condition submit button stills works. I am unable to stop the submit if required fields are empty. Here is the small piece of my code.
HTML:
<form class="pa-form" action="confirmed" method="post" id="my-form">
<fieldset>
<?php for($i=1;$i<=3;$i++){ ?>
<div class="flabel-control">
<input data-toggle="floatLabel" data-value="" name="myForm[first_name][]" class="firstname form-control" type="text" id="first-name<?=$i?>" required placeholder="First name" spellcheck="false">
</div>
<div class="flabel-control">
<input data-toggle="floatLabel" data-value="" name="myForm[last_name][]" class="firstname form-control" type="text" id="last-name<?=$i?>" required placeholder="Last name" spellcheck="false">
</div>
<br>
<?php };?>
<div class="btn-holder">
<input type="submit" id="submitBtn" class="btn btn-default text-uppercase" value="Confirm">
</div>
</fieldset>
</form>
Js:
$("#my-form").validate({
validClass: "valid",
errorClass: "error",
rules: {
'myForm[first_name][]': "required",
'myForm[last_name][]': "required",
},
messages: {
'myForm[first_name][]': "First name is required",
'myForm[last_name][]': "Last name is required",
}
}
});
jquery-validate requires that each element have a unique name. So put the for loop index into the names.
<?php for($i=1;$i<=3;$i++){ ?>
<div class="flabel-control">
<input data-toggle="floatLabel" data-value="" name="myForm[first_name][<?=$i?>]" class="firstname form-control" type="text" id="first-name<?=$i?>" required placeholder="First name" spellcheck="false">
</div>
<div class="flabel-control">
<input data-toggle="floatLabel" data-value="" name="myForm[last_name][<?=$i?>]" class="firstname form-control" type="text" id="last-name<?=$i?>" required placeholder="Last name" spellcheck="false">
</div>
<br>
<?php };?>
You don't need to list the elements specifically in the rules, because the plugin automatically processes the required attributes in the elements. But if you want to, you can do:
var rules = {}, messages = {};
for (var i = 1; i <= 3; i++) {
rules['myForm[firstname][' + i + ']'] = 'required';
messages['myForm[firstname][' + i + ']'] = 'First name is required';
rules['myForm[lastname][' + i + ']'] = 'required';
messages['myForm[lastname][' + i + ']'] = 'Last name is required';
}
$("#my-form").validate({
validClass: "valid",
errorClass: "error",
rules: rules,
messages: messages
}
});