JQuery validation accepts even if input contains only whitespaces - javascript

I am having trouble validating if input fields contains only whitespaces. I have specified the required rule for the required fields but it still works if I just type spaces. also, noSpace rule for username field does not seem to work. It disables validation for the other fields. Here is my markup.
<form method=post class="form-auth-small" action="../php/controller/registration_controller.php">
<div class="form-group row m-t-10px">
<div class="col-sm-6 text-left m-b-5px">
<label><h5>RANK: </h5></label>
<select class="form-control" name="rank" required="required">
<option value="rank1">NUP</option>
<option value="rank2">PO1</option>
<option value="rank3">PO2</option>
<option value="rank4">PO3</option>
<option value="rank5">SPO1</option>
<option value="rank6">SPO2</option>
<option value="rank7">SPO3</option>
<option value="rank8">SPO4</option>
<option value="rank9">PINSP</option>
<option value="rank10">PSINSP</option>
<option value="rank11">PCINSP</option>
<option value="rank12">PSUPT</option>
<option value="rank13">PSSUPT</option>
<option value="rank14">PCSUPT</option>
<option value="rank15">PDIR</option>
<option value="rank16">PDDG</option>
<option value="rank17">PDG</option>
</select>
</div>
<div class="col-sm-6 text-left m-b-5px">
<label><h5>USERNAME: </h5></label>
<input class="form-control" name="username" placeholder="Username must only contain characters [A-Z] and numbers [0-9]" type="text" minlength="1" required="required">
</div>
<div class="clearfix"></div>
<div class="col-sm-6 text-left m-b-5px">
<label><h5>FIRST NAME: </h5></label>
<input class="form-control" name="fname" type="text" minlength="1" required="required">
</div>
<div class="col-sm-6 text-left m-b-5px">
<label><h5>PASSWORD: </h5></label>
<input class="form-control" name="pwd" placeholder="Choose a strong password" type="password" minlength="1" required="required">
</div>
<div class="clearfix"></div>
<div class="col-sm-6 text-left m-b-5px">
<label><h5>MIDDLE NAME: </h5></label>
<input class="form-control" name="mname" type="text" minlength="1" required="required">
</div>
<div class="col-sm-6 text-left m-b-5px">
<label><h5>EMAIL: </h5></label>
<input class="form-control" name="email" type="email" minlength="1" required="required">
</div>
<div class="clearfix"></div>
<div class="col-sm-6 text-left m-b-5px">
<label><h5>LAST NAME: </h5></label>
<input class="form-control" name="lname" type="text" minlength="1" required="required">
</div>
</div>
<div class="form-group clearfix m-b-5px">
<button type="submit" name="btnRegister" class="btn btn-primary btn-lg btn-block">REGISTER</button>
</div>
<div class="bottom m-b-15px">
<span><i class="fa fa-lock"></i> Already have an account? Sign in.</span>
</div>
</form>
JS (Without noSpace rule)
$(document).ready(function () {
$('.form-auth-small').validate({
rules: {
rank: {
required: true
},
username: {
required: true,
minlength: 3
},
fname: {
required: true
},
mname: {
required: true
},
lname: {
required: true
},
pwd: {
required: true
},
email: {
required: true
}
},
errorElement: "em",
errorPlacement: function ( error, element ) {
// Add the `help-block` class to the error element
error.addClass( "help-block" );
// Add `has-feedback` class to the parent div.form-group
// in order to add icons to inputs
element.parents( ".col-sm-5" ).addClass( "has-feedback" );
error.insertAfter( element );
// Add the span element, if doesn't exists, and apply the icon classes to it.
if ( !element.next( "span" )[ 0 ] ) {
$( "<span class='glyphicon glyphicon-remove form-control-feedback'></span>" ).insertAfter( element );
}
},
success: function ( label, element ) {
// Add the span element, if doesn't exists, and apply the icon classes to it.
if ( !$( element ).next( "span" )[ 0 ] ) {
$( "<span class='glyphicon glyphicon-ok form-control-feedback'></span>" ).insertAfter( $( element ) );
}
},
highlight: function ( element, errorClass, validClass ) {
$( element ).parents( ".col-sm-6" ).addClass( "has-error" ).removeClass( "has-success" );
$( element ).next( "span" ).addClass( "glyphicon-remove" ).removeClass( "glyphicon-ok" );
},
unhighlight: function ( element, errorClass, validClass ) {
$( element ).parents( ".col-sm-6" ).addClass( "has-success" ).removeClass( "has-error" );
$( element ).next( "span" ).addClass( "glyphicon-ok" ).removeClass( "glyphicon-remove" );
}
});
});
DEMO
Thank you in advance!

Just add this method before your jQuery validate function run::
jQuery.validator.addMethod("noSpace", function(value, element) {
return value.indexOf(" ") < 0 && value != "";
}, "No space please and don't leave it empty");
AND use
noSpace: true
for each field you want.

Try this
$(document).ready(function() {
jQuery.validator.addMethod("noSpace", function(value, element) {
return value.indexOf(" ") < 0 && value != "";
}, "No space");
$(".form-auth-small").validate({
rules: {
username : {
noSpace: true
}
}
});
})

$(".form-auth-small").validate({
rules: {
username : {
required: true,
normalizer: function(value) {
return $.trim(value);
}
}
}
});
use normalizer , in which it will trim or remove all whitespaces.
simple solution.enjoy your day

Related

Error Placement Issue for the required fields

I have an issue with error placement for the required field and it overlaps exactly on the labels of the field and I'm using bootstrap modal with class form-label-group and it works fine if I remove the class. I want to show the error messages within the span of each input fields. It's really hard for the users to check the field names when I validate the form before submit.
$('#Test').validate({
errorElement: 'span', //default input error message container
errorClass: 'help-block', // default input error message class
focusInvalid: false, // do not focus the last invalid input
ignore: "",
rules: {
FName: {
required: true
},
LName: {
required: true
}
},
invalidHandler: function(event, validator) { //display error alert on form submit
},
highlight: function(element) { // hightlight error inputs
$(element)
.closest('.form-group').addClass('has-error'); // set error class to the control group
},
success: function(label) {
label.closest('.form-group').removeClass('has-error');
label.remove();
},
errorPlacement: function(error, element) {
if (element.closest('.input-icon').length === 1) {
error.insertAfter(element.parent("span"));
} else {
error.insertAfter(element.parent("span"));
}
},
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="modal-body">
<form id="Test" action="#" class="addForm floating-labels m-t-40">
<div class="row">
<div class="col-md-3 col-lg-3 col-3">
<div class="form-group">
<input type="text" id="FName" name="FName" value="" class="form-control" required="required" autofocus="autofocus" maxlength="50">
<span class="bar"></span>
<label for="FName">First Name*</label>
</div>
</div>
<div class="col-md-3 col-lg-3 col-3">
<div class="form-group">
<input type="text" id="LName" name="LName" value="" class="form-control" required="required" autofocus="autofocus" maxlength="50">
<span class="bar"></span>
<label for="LName">Last Name*</label>
</div>
</div>
</div>
</div>
Thanks Swati and it worked. The issue was in one of my class, which was causing the issue.
element.parent("span") to element.next("span")

issue in Bootstrap 4 validation on select field

I'm new to jQuery and Bootstrap, I'm using jquery and Bootstrap 4 for validation of my form modal, whenever there is an error it must show the error below the corresponding fields, but in my case the select field gets overwritten by the error and select field disappears but it works fine for input field.
here have a look and if you want to have a close look on image just click on it..
As you can see the select fields get overwritten by the fieldError but it's fine for input field.
here's my jQuery validation code:
$(function(){
setCategorySelect();
$(document).on('shown.bs.modal','#manageItemsModal', function () {
$('#manageItemsModal #btnSubmit').on('click', function(){
if (validateForm()) {
messageSuccess("Very well");
} else {
messageError("Oops!!");
}
});
});
});
function validateForm() {
var validationStatus = true;
if ($('#manageItemsForm #selectedCategory').val().length == 0) {
showFieldError(('#manageItemsForm #selectedCategory'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #selectedCategory').focus() };
validationStatus = false;
}
if ($('#manageItemsForm #selectedBrandModel').val().length == 0) {
showFieldError(('#manageItemsForm #selectedBrandModel'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #selectedBrandModel').focus() };
validationStatus = false;
}
if ($('#manageItemsForm #serialNo').val().length == 0) {
showFieldError(('#manageItemsForm #serialNo'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #serialNo').focus() };
validationStatus = false;
}
if ($('#manageItemsForm #selectedVendor').val().length == 0) {
showFieldError(('#manageItemsForm #selectedVendor'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #selectedVendor').focus() };
validationStatus = false;
}
if ($('#manageItemsForm #selectedBranch').val().length == 0) {
showFieldError(('#manageItemsForm #selectedBranch'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #selectedBranch').focus() };
validationStatus = false;
}
return validationStatus;
}
function showFieldError(element, message) {
$(element).addClass('is-invalid');
$(element).next().html(message);
$(element).next().show();
}
function clearFieldError(element) {
$(element).removeClass('is-invalid');
$(element).removeAttr('required');
$(element).next().html('');
}
function setCategorySelect() {
var $categorySelect = $('#manageItemsForm #selectedCategory').selectize({
selectOnTab: true,
closeAfterSelect: true,
persist: false,
create: false,
valueField: 'id',
labelField: 'text',
options: [],
preload: true,
onInitialize : function() {
var self = this;
$.ajax({
url: '/assetCategory/search',
type: 'POST',
dataType: 'json',
data: {
searchText: '*'
},
error: function() {
callback();
},
success: function(res) {
self.addOption(res.data);
}
});
},
load: function(query, callback) {
if (query.length <= 2) return callback();
$.ajax({
url: '/assetCategory/search',
type: 'POST',
dataType: 'json',
data: {
searchText: query + "*"
},
error: function() {
callback();
},
success: function(res) {
console.log(res.data);
callback(res.data);
$categorySelect.refreshItems();
},
fail : function() {
callback();
}
});
}
});
}
here's my HTML:
<div class="modal-body">
<form id="manageItemsForm">
<input type="hidden" id="id" name="id">
<div class="row">
<div class="col-4">
<div class="form-group">
<label for="selectedCategory" class="col-form-label"><span class="text-danger">* </span>Category</label>
<select class="form-control" name="selectedCategory" id="selectedCategory"></select>
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-8">
<div class="form-group">
<label for="selectedBrandModel" class="col-form-label"><span class="text-danger">* </span>Brand & Model</label>
<select class="form-control" name="selectedBrandModel" id="selectedBrandModel"></select>
<div class="invalid-feedback"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-4">
<div class="form-group">
<label for="serialNo" class="col-form-label"><span class="text-danger">* </span>Serial No.</label>
<input type="text" class="form-control" id="serialNo" name="serialNo">
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-8">
<div class="form-group">
<label for="description" class="col-form-label">Description</label>
<input type="text" class="form-control" id="description" name="description">
<div class="invalid-feedback"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-6">
<div class="form-group">
<label for="selectedVendor" class="col-form-label"><span class="text-danger">* </span>Purchase Vendor</label>
<select class="form-control" name="selectedVendor" id="selectedVendor"></select>
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="selectedVendor" class="col-form-label"><span class="text-danger">* </span>Purchase Date</label>
<div class="input-group date" data-date-format="dd-M-yyyy">
<input type="text" class="form-control" id="purchaseDate" name="purchaseDate" />
<span class="input-group-text input-group-append input-group-addon"><i class="simple-icon-calendar"></i></span>
</div>
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="supportTillDate" class="col-form-label"><span class="text-danger">* </span>Support till date</label>
<div class="input-group date" data-date-format="dd-M-yyyy">
<input type="text" class="form-control" id="supportTillDate" name="supportTillDate" />
<span class="input-group-text input-group-append input-group-addon"><i class="simple-icon-calendar"></i></span>
</div>
<div class="invalid-feedback"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-9">
<div class="form-group">
<label for="selectedBranch" class="col-form-label"><span class="text-danger">* </span>Branch</label>
<select class="form-control" name="selectedBranch" id="selectedBranch"></select>
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-3">
<label for="purchasePrice" class="col-form-label">Purchase Price</label>
<div class="input-group">
<div class="input-group-prepend"><span class="input-group-text input-group-addon" style="padding: 0.4rem 0.75rem 0.3rem 0.75rem;">₹</span></div>
<input id="purchasePrice" name="purchasePrice" type="text" class="form-control" aria-label="Amount" style="text-align:right;">
</div>
<div class="invalid-feedback"></div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button id="btnSubmit" type="button" class="btn btn-primary">Save</button>
</div>
</div>
By the way I am using jQuery in Spring boot and everything is working fine(save, update, delete) except for validation from jQuery.
Please help!!
I can't see working code because you using some external references like selectize.
I suggest you get used to "snippets" to provide code.
Bytheway, your problem seems to be just about styles. I can't know, but my bet is you just need to provide a css style for
.select::after.error {
color:red;
}
You can inspect and copy CSS code.
The problem is in Your HTML, the nodes of your .input-group does not have allways the same structure. In some cases you have .invalid-feedback just after the input such as this HTML
<div class="form-group">
<label for="serialNo" class="col-form-label"><span class="text-danger">*
</span>Serial No.</label>
<input type="text" class="form-control" id="serialNo" name="serialNo">
<div class="invalid-feedback"></div>
</div>
For other fields the .invalid-feedback isn't after the input but outside from .form-group. take a look
<div class="input-group date" data-date-format="dd-M-yyyy">
<input type="text" class="form-control" id="purchaseDate" name="purchaseDate" />
<span class="input-group-text input-group-append input-group-addon">
<i class="simple-icon-calendar"></i>
</span>
</div>
<div class="invalid-feedback"></div>
This difference in HTML structure of the form made your showFieldError() and clearFieldError() not working allways as you expected, because $(element).next() don't catch the right DOM node for insert/remove the validation message. So in some cases clearFieldError remove the wrong HTML tag and this can make your selects disappear
function showFieldError(element, message) {
$(element).addClass('is-invalid');
$(element).next().html(message);
$(element).next().show();
}
function clearFieldError(element) {
$(element).removeClass('is-invalid');
$(element).removeAttr('required');
$(element).next().html('');
}
So you have to fix Your HTML to obtain the same structure for all fields. Put the <div class="invalid-feedback"></div> allways just below the select or input field. Otherwise you have to change the selector that you pass to showFieldError() and clearFieldError() functions according to your HTML
Otherwise a simply approach is to add a ID to divs with class .invalid-feedback, an ID which you can easily manage by his related input ID, something like
<div class="input-group date" data-date-format="dd-M-yyyy">
<input type="text" class="form-control" id="purchaseDate" name="purchaseDate" />
<span class="input-group-text input-group-append input-group-addon">
<i class="simple-icon-calendar"></i>
</span>
</div>
<div id="purchaseDate_err_mex" class="invalid-feedback"></div>
in this way you can pass the input name to your functions and them becomes
function showFieldError(input_id, message) {
$('#'+input_id).addClass('is-invalid');
$('#'+ input_id +'_err_mex').html(message).show();
}
function clearFieldError(input_id) {
$('#'+input_id).removeClass('is-invalid');
//$('#'+input_id).removeAttr('required');
/* don't need to remove required attribute from mandatory fields */
$('#'+ input_name +'_err_mex').html('').hide();
}
and the validation function
function validateForm() {
var validationStatus = true;
if ($('#selectedCategory').val().length == 0) {
showFieldError('selectedCategory', 'Must not be blank');
if (validationStatus) { $('#selectedCategory').focus() };
validationStatus = false;
}
........
return validationStatus;
}
You only check if the length of all fields is more than 0, so you can validate the entire form within a loop
function validateForm() {
var validationStatus = true;
var form_inputs = $('#manageItemsForm input, #manageItemsForm select')
$.each(form_inputs,function(){
var input_id = $(this).attr('name');
clearFieldError(input_id);
if ($.trim($(this).val()).length == 0 && $(this).is("[required]")) {
showFieldError(input_id, 'Must not be blank');
if (validationStatus) { $('#'+input_id).focus() };
validationStatus = false;
}
});
return validationStatus;
}

Remove jQuery element validation from a specific element

I have form with jQuery validation defined as follows.
//#costCalculation is a form id
$('#costCalculation').validate({
onsubmit: false, //To prevent validation during form submit
errorClass: "my-error-class",
rules: {
adSizeFull: {
required: true
},
fullAdNo: {
required: true
}
},
messages: {
adSizeFull: "Please select Full adsize",
fullAdNo: "Please select total Ads(Full)"
},
submitHandler: function (form) { // for demo
//alert('valid form');
return true;
}
});
I have a form with select box like this
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label class="control-label col-xs-4">Ads(Full):</label>
<div class="col-xs-8">
<select name="adSizeFull" id="fullads-list" class="form-control" onchange="fullAdSizeChange()">
<option value="">--Select--</option>
</select>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="control-label col-xs-4" for="fullAdNo">#:</label>
<div class="col-xs-8">
<select name="fullAdNo" id="fulladnos-list" class="form-control" onchange="fullAdNoChange()">
<option value="">--Select--</option>
</select>
</div>
</div>
</div>
</div>
I would like to remove validation in the following scenario JS
function fullAdSizeChange() {
var adSizeFull = $("#fullads-list").val();
var fullAdNo = $("#fulladnos-list").val();
if(adSizeFull == "" && fullAdNo == "") {
$("#fullads-list").rules("remove", "required");
$("#fulladnos-list").rules("remove", "required");
}
}
How to remove the validation from specific elements if the form is specified as above??
I haven't copied the entire code. There may problems in syntaxes. I need guidelines only to implement this
jQuery Validate actually directly supports dependency expressions.
All you need to do is change your validate options like this:
parent: {
required: function(element) {
return $("#age").val() < 13;
// Makes "parent" required only if age is below 13.
}
Full Example:
$( "#myform" ).validate({
rules: {
age: {
required: true,
min: 3
},
parent: {
required: function(element) {
return $("#age").val() < 13;
}
}
}
});
}
just add the required class in both select box class no need to add change event
<select name="adSizeFull" id="fullads-list" class="form-control required" onchange="fullAdSizeChange()">
<option value="">--Select--</option>
</select>

jquery validation for select box onchange

i design show/hide div select box using select2 and validate using jquery validation plugin. this worked but when i select empty value(select a color) validation show success (green color) but if i click submit button i see red color.
JS:
$(document).ready(function () {
$(".lstColors").change(function () {
$('div.box').hide();
$('div.box.' + $(this).val()).show();
}).change();
$('form').validate({
rules: {
firstname: {
minlength: 3,
maxlength: 15,
required: true
},
lastname: {
minlength: 3,
maxlength: 15,
required: true
}
},
highlight: function (element, errorClass, validClass) {
if (element.type === "radio") {
this.findByName(element.name).addClass(errorClass).removeClass(validClass);
} else {
$(element).closest('.form-group').removeClass('has-success has-feedback').addClass('has-error has-feedback');
$(element).closest('.form-group').find('i.fa').remove();
$(element).closest('.form-group').append('<i class="fa icon-plane icon-2x form-control-feedback"></i>')
}
},
unhighlight: function (element, errorClass, validClass) {
if (element.type === "radio") {
this.findByName(element.name).removeClass(errorClass).addClass(validClass);
} else {
$(element).closest('.form-group').removeClass('has-error has-feedback').addClass('has-success has-feedback');
$(element).closest('.form-group').find('i.fa').remove();
$(element).closest('.form-group').append('<i class="fa icon-plane icon-2x form-control-feedback"></i>');
}
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function (error, element) {
if (element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
$('form').on('submit', function () {
$(this).addClass('submitted');
});
$("#lstColors").select2({
placeholder: "Select a Color",
triggerChange: true,
allowClear: true,
width: "200px"
}).on('change', function () {
if ($('form').hasClass('submitted')) $('form').valid();
});
});
HTML:
<form>
<div class="form-group">
<label class="control-label" for="firstname">Nome:</label>
<div class="col-md-6">
<div class="row">
<div class="col-md-3">
<div class="input-group select2-bootstrap-prepend"> <span class="input-group-addon"><i class=" icon-male"></i></span>
<input class="form-control" placeholder="Insira o seu nome próprio" name="firstname" type="text" />
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="lstColors" class="control-label">Favorite Colors:</label>
<div class="col-md-6">
<div class="row">
<div class="col-md-3">
<div class="input-group select2-bootstrap-prepend">
<select id="lstColors" class="lstColors required">
<option value=""></option>
<option value="red" selected>Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>
<div class="red box">test</div>
<div class="green box">You have selected <strong>green option</strong> so i am here</div>
<div class="blue box">You have selected <strong>blue option</strong> so i am here</div>
</div>
</div>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Now, i need to show red color after choose empty value(on change). how do can fix this ?
JSFIDDLE
Add new validation method right after the ready function
$.validator.addMethod("valueNotEquals", function(t, n, r) {
return t != r
}, $.validator.format("Invalid val is supplied."));
Validation rules should look like
rules: {
firstname: {
minlength: 3,
maxlength: 15,
required: true
},
lastname: {
minlength: 3,
maxlength: 15,
required: true
},
mySelect: {
valueNotEquals: 0
}
},
And of course do not forget to add name attribute to your select like in the rules declared above + placeholder option's value should be the value provided in rules (in this case 0)
<select id="lstColors" name="mySelect" class="lstColors required">
<option value="0"></option>
UPDATE
I noticed that if the value of placeholder option is changed the placeholder disappears, so I searched for another solution and found one:
$(".lstColors").on('select2-removed', function () {
if ($('form').hasClass('submitted')) $('form').valid();
});
Checkout the fiddle

How to display calender on cloned form using jquery

I have an date input area using Bootstrap-dateinput
<div class="form-group row">
<div class="col-xs-8">
<label class="control-label">Date</label>
<div class="input-group date" id="dp3" data-date="12-02-2014" data-date-format="mm-dd-yyyy">
<input class="form-control" type="text" required="" placeholder="Date" name="date[]" value="">
<span class="input-group-addon">
<i class="glyphicon glyphicon-calendar"></i>
</span>
</div>
</div>
</div>
Jquery Script To clone this form:
<script type="text/javascript">
$( document ).on( 'click', '.btn-add', function ( event ) {
event.preventDefault();
var field = $(this).closest( '.form-group' );
var field_new = field.clone();
$(this)
.toggleClass( 'btn-default' )
.toggleClass( 'btn-add' )
.toggleClass( 'btn-danger' )
.toggleClass( 'btn-remove' )
.html( '-' );
field_new.find( 'input' ).val( '' );
field_new.insertAfter( field );
} );
</script>
And Script to display calender:
<script type="text/javascript">
$('.input-group .date').datepicker({
...
});
</script>
But when New input area is created it do not show calender when clicked
I tried adding onclick
$(".input-group .date").click(function(){
$('.input-group .date').datepicker({
...
});
But yet seems there is some problem Can you please tell whats wrong and how to fix it ?
Try This:
<input class="form-control" type="text" required="" placeholder="Date" name="date[]" value="" onclick="$(this).datepicker({
...
});">

Categories

Resources