I have a form, styled with bootstrap, that contains multiple fields (tel number, date, start time, end time...), meant to book bicycles.
When those fields are changed, a script checks throught ajax if a bicycle is free and change the class of a button (act as submit by default) from .btn-danger (red - no bicycle available) to .btn-success (green - You got one !) accordingly :
<form id='resa_velo_form' name='resa_velo_form' method='POST' action='index.php?app=resa&ctrl=AccueilUserCtrl&action=enregistreResaVelo'>
<div class='form-group col-md-3'>
<label for="velo_date">Date d'emprunt : </label>
<div class='input-group date' id='datetimepicker_deb'>
<input type="text" id="velo_date" name="date_start" autocomplete="off" class="form-control" required>
<span class="input-group-addon">
<span class=" fa fa-calendar"></span>
</span>
</div>
</div>
<div class='form-group col-md-2'>
<label for="velo_time_start">Départ :</label>
<input id="velo_time_start" class="timepicker_input velo spinner" name="time_start" value="8:30" required>
</div>
<div class='form-group col-md-2'>
<label for="velo_time_end">Retour : </label>
<input id="velo_time_end" class="timepicker_input velo spinner" name="time_end" value="9:30" data-parsley-timeissup="#velo_time_start" required>
</div>
<div class='form-group col-md-5'>
<label> </label>
<button id="disponibilite_velo" class="error_resa btn btn-danger col-md-12" data-parsley-success='btn-success' required>Choisissez une date</button>
</div>
</form>
I managed to use Parsley to validate this form and even got to apply .has-error classes to form-group :
$('#resa_velo_form').parsley({
successClass: "has-success",
errorClass: "has-error",
classHandler: function(el) {
return el.$element.closest(".form-group");
}
})
I'm using successfully a custom validator on start and end time :
window.Parsley.setLocale('fr');
window.Parsley.addValidator('timeissup', {
requirementType: 'string',
validateString: function(value, requirement) {
time1 = $(requirement).val().split(/:/);
time1 = time1[0] * 3600 + time1[1] * 60;
time2 = value.split(/:/);
time2 = time2[0] * 3600 + time2[1] * 60;
return (time2 > time1);
},
messages: {
en: 'This value should be higher than start time.',
fr: "Cette valeur doit être supérieure à l'heure de départ."
}
});
BUT THEN...
I tried to make a custom validator to check the class of the button :
window.ParsleyConfig = {
excluded: 'input[type=hidden], :hidden, input[type=reset]',
inputs: 'input, textarea, select, input[type=button], button, input[type=submit]'
};
window.Parsley.addValidator('success', {
requirementType: 'string',
validateString: function(value, requirement) {
console.log('ok - Parlsey Valid Success');
return ($('#disponibilite_velo').hasClass(requirement));
},
messages: {
en: 'This button should be green !',
fr: "Ce bouton doit être vert !"
}
});
And it never works, Parlsey doesn't seems to use this validator, but still checks fields required and "timeissup" custom validator.
In fact, I managed to make it work by attaching it to an input field, but that's not the point.
Any help, please ?
Got it to work !
Contrary to this answer, you need to define excluded and inputs in the form validator itself :
$('#resa_velo_form').parsley({
successClass: "has-success",
errorClass: "has-error",
excluded: 'input[type=reset]',
inputs: 'input, textarea, select, button',
classHandler: function(el) {
return el.$element.closest(".form-group");
}
});
Other important thing : even if it's a button, you need the required attribute and a value different from '' (empty):
<button id="disponibilite_velo" class="error_resa btn btn-danger col-md-12" data-parsley-inputsuccess='btn-success' value='*' required>Choisissez une date</button>
Maybe not so clean, but... working !
Related
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();
}
});
});
I'm using form, where i have remove function. It is working fine but i want the fields value to be clear when remove function triggered. Because i'm also sending input values to my php script.
This is html
<div class="form-group">
<div class="col-xs-12 col-sm-6 childname">
<div class="field text-left">
<label class="text-left">Child name</label>
<input class="thevoornaam character" name="voorname[]" type="text" placeholder="Voornaam"/>
</div>
</div>
<div class="col-xs-12 col-sm-6 dateofbirth">
<div class="field text-left">
<label class="text-left">Date of birth</label>
<input type="text" class="date" name="date[]" placeholder="DD / MM / JJJJ" onkeyup="showHint(this.value,'stepname')" />
<!-- <input type="text" size="50" id="URL" onchange="getDoB(this.value)"/> -->
</div>
</div>
</div>
<a class="delete removeButton" href="#" onmouseup="showHint('close','stepname');"><i class="fa fa-times"></i></a>
Here is my js code
(document).ready(function() {
$('#taskForm')
.bootstrapValidator({
framework: 'bootstrap',
fields: {
'task[]': {
// The task is placed inside a .col-xs-6 element
row: '.col-xs-6',
validators: {
notEmpty: {
message: 'The task is required'
}
}
},
'date[]': {
// The due date is placed inside a .col-xs-6 element
row: '.col-xs-6',
validators: {
date: {
format: 'DD/MM/YYYY'
// message: 'Fill valid date of birth'
}
}
}
}
})
.on('added.field.fv', function(e, data) {
if (data.field === 'date[]') {
// The new due date field is just added
// Create a new date picker
data.element
.parent()
// .datepicker({
// format: 'dd/mm/yyyy'
// })
.on('changeDate', function(evt) {
// Revalidate the date field
$('#taskForm').bootstrapValidator('revalidateField', data.element);
});
}
})
// Add button click handler
.on('click', '.addButton', function() {
var $template = $('#taskTemplate'),
$clone = $template
.clone(true,true)
.removeClass('hide')
.removeAttr('id')
.insertBefore($template);
$("#stepname").addClass("disabled")
// Add new fields
// Note that we DO NOT need to pass the set of validators
// because the new field has the same name with the original one
// which its validators are already set
$('#taskForm')
.bootstrapValidator('addField', $clone.find('[name="task[]"]'))
.bootstrapValidator('addField', $clone.find('[name="date[]"]'))
})
// Remove button click handler
.on('click', '.removeButton', function() {
var $row = $(this).closest('.form-group');
// Remove fields
$('#taskForm')
.bootstrapValidator('removeField', $row.find('[name="task[]"]').val(''))
.bootstrapValidator('removeField', $row.find('[name="date[]"]').val(''));
// Remove element containing the fields
$row.remove();
});
});
Here i'm trying to clear the values but it is not working. Can anyone help here what i'm doing miskate?
Thanks is advance
If all you needed to do is a field clear...
I'm iterating around each one with .each and setting its value to an empty string😊
ES6
$('.delete.removeButton').click(() => {
$('.form-group').find('input').each((i, el) => {
$(el).val('')
})
})
ES5
$('.delete.removeButton').click(function () {
$('.form-group').find('input').each(function (i, el) {
$(el).val('')
})
})
use button instead of anchor tag and add onclick= "clearInput()" into it:
<input type="text" id = "clId" class="date" name="date[]" placeholder="DD / MM / JJJJ" onkeyup="showHint(this.value,'stepname')" />
<button onclick= "clearInput()" >clear value</button>
then in js try like this:
function clearInput(){
$('#clId').val('');
}
follow this given way. hope your problem will be sorted out.
I am using the latest version of ParsleyJS and tried the example from doc, just copy pasted it into my code but it wont work. I actually made my own validator but its not working, so I tried to copy paste the exact example but it doesn't work as well.
I am working with Laravel and here's my form and js code.
<div class="form-group">
<label>Name of my school</label>
{{ Form::text('edu[institute]', null, ['class' => 'form-control', 'data-parsley-myValidator' => '']) }}
</div>
window.Parsley.addValidator('myValidator', {
validateString: function(value) {
return value.split('').reverse().join('') === value;
},
messages: {
en: 'This string is not the reverse of itself',
fr: "Cette valeur n'est pas l'inverse d'elle même."
}
})
I have just torn my hair, WHY WOULD THIS NOT WORK?
Laravel blade output of form field:
<input class="form-control" data-parsley-myvalidator="" name="edu[institute]" type="text">
EDIT:
This form field is inside a Bootstrap Modal.
Their example seems to work fine. I still can't reproduce your issue.
window.Parsley.addValidator('palindrome', {
validateString: function(value) {
return value.split('').reverse().join('') === value;
},
messages: {
en: 'This string is not the reverse of itself',
fr: "Cette valeur n'est pas l'inverse d'elle même."
}
});
<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/parsley.js/2.7.2/parsley.min.js"></script>
<form data-parsley-validate="">
<label>Please enter a palindrome:</label>
<input type="text" data-parsley-palindrome="">
<input type="submit" class="btn">
</form>
$(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" />
I have html like these
<form class="form-filter" id="form-filter-excel" role="form">
<div class="row">
<div class="col-md-4 col-sm-5">
<label>Date range</label>
<div class="input-group input-daterange datepicker">
<input id="fRange" name="fRange" class="form-control input-sm" type="text">
<span class="input-group-addon bg-primary">to</span>
<input id="sRange" name="sRange" class="form-control input-sm" type="text">
</div>
</div>
<div class="col-md-2 col-sm-1">
<label>
</label>
<a class="btn btn-wide btn-primary form-control" href="#" id="btnexport" ><i class="fa fa-file-excel-o"></i> Export To Excel</a>
</div>
</div>
</form>
end here my screen shoot
My question i wanna use validate() on jquery, but i'm kinda stuck i wanna use class= "input-daterange" as field, and the input fRange and sRange as required. How do i did that, if i using fRange and sRange as field, the error massage show up mess. Any idea??
UPDATE :
Sorry for not unclear my question
I'm using jquery validate like these
$('#form-filter-excel').validate({
highlight: function(element) {
$(element).closest('.form-group').prop('required',true);
},
unhighlight: function(element) {
$(element).closest('.form-group').prop('required',false);
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
},
rules: {
fRange: {
required: true,
date: true
},
sRange: {
required: true,
date: true
}
},
messages: {
fRange: "Please insert these input",
sRange: "Please insert these input"
},
});
$('#btnexport').click(function() {
$('#form-filter-excel').valid();
if($('#form-filter-excel').valid()==true)
{
var Fod = $('#fRange').val();
var Tod = $('#sRange').val();
window.open(host+"ajax/excelpoinfo?Fod=" + Fod +"&Tod=" + Fod, '_blank');
}
});
but the problem is the error massage not show under my input but show error like these on my screen
What i need is the error massage show on under each my input.
UPDATE:
I change my mind, i'm using sweet alert then, tq for helping. And for Mayank Pandeyz, u didnt see my question clearly, like i said, that not helping, even u said change replacement. Still not work.
On both the textbox provide the name attribute with its values like:
<form id="frmDetails" name="frmDetails">
<input type="textbox" name="fRange">
<input type="textbox" name="sRange">
</form>
And put the validation code on these like:
$('#frmDetails').validate({
rules:
{
fRange: {
required: true
},
sRange: {
required: true
}
},
messages:
{
fRange: {
required: "Please select fRange"
},
sRange: {
required: "Please select sRange"
}
}
});
Working Fiddle