How to not allow generate error element - javascript

I work with jquery.validate and I search a way how not allow to validator to generate error element.
$("#smsForm").validate({
highlight: function (element) {
$(element).addClass("notvalid");
},
unhighlight: function (element) {
$(element).removeClass("notvalid");
}
});
I just want to add not valid class to input field without generate any input elements.
But validator add :
<label for="phoneNumber" generated="true" class="error">Phone</label>
for example if phone number not correct

I think that if you set the errorElement option passed to .validator() to anything other than "label", then the validate plugin will not generate an error element for you. For example:
$("#smsForm").validate({
errorElement: "",
highlight: function (element) {
$(element).addClass("notvalid");
},
unhighlight: function (element) {
$(element).removeClass("notvalid");
}
});

The error element in jQuery validate is just a css class, i.e.
<input id="email" class="email error" type="text">
For example, in above, the class is "email error".
If you don't want the error element to "show up" you can just change the css style in your stylesheet:
.error {
background-color: #fff; /* make the pink/red colour white */
display: none; /* another way to hide it...*/
}
If what you are asking is how to "hide" the error message...if you don't want the .error class added, that's something else.

Related

Re-validate field after changing input

We are using HTML form validation (and we explicitly do NOT want do use jQuery validate plugin...). Currently I am able to mark invalid/empty fields after Submit. I do it this way:
if(document.addEventListener){
document.addEventListener('invalid', function(e){
e.target.className += ' invalid';
}, true);
}
But the marking remains after the user enters information to a field. How can I remove the className, let's say, onBlur?
Maybe I can just add the following CSS classes:
input:invalid:focus,
input.invalid{
border: solid 1px #f00; /* red border */
}
input:valid {
border: 1px solid #ced4da; /* reset to default border color */
}
At least this seems to work.
Are there any smarter solutions?
Add to the blur event within the invalid event handler like so:
document.addEventListener("invalid", function(e) {
const oldClassName = e.target.className;
e.target.className += "-invalid";
e.target.addEventListener("blur", function(e) {
e.target.className = oldClassName;
}, { once: true });
});
The { once: true } option at the end ensures that the event listener gets taken off once the blur happens.
The browser automatically adds/removes the :invalid pseudo selector for you https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid, just style the form fields as you would for the regular case (not invalid) and invalid case (using the :invalid selector)

Change the text color of my input field when using the standard datepicker in Edge and Chrome

I want to change the background of my date field on my form when I make a selection from the standard datepicker in Edge and Chrome.
my jquery
$(document).ready(function () {
$(":input").change(function () {
toggleEmptyInputs($(this));
});
});
my date field is:
<input type="date" name="Birthday" class="date mandatory empty validationerror" id="i105">
The ID is automatically made and can change for different forms. So I need to use the name or.....
What I really want is when I use the datepicker that the empty part in the class is removed (basically that is what the toggleEmptyInputs function does in my jquery).
I tried to use :
$(":input").datepicker({
onSelect: function() {
toggleEmptyInputs($(this));
}
});
but this does not work and also produce an error in firefox as Uncaught TypeError: $(...).datepicker is not a function.
Thanks in advance for your help
the toggle function is
function toggleEmptyInputs(inputElement) {
if (inputElement.val()) {
inputElement.removeClass("empty");
inputElement.closest(".col").removeClass("hidelabel");
} else {
inputElement.addClass("empty");
inputElement.closest(".col").addClass("hidelabel");
}
}
and works fine for all other fields.
the fiddle works fine because of the .empty:after {content: "empty"} in the css
SO I am going to incorporate this in my removeClass function
Thanks Scimonster
To facilitate: "I want to change the background of my date field on my form when I make a selection" you can simply add a class.
Example: with colorme class
$(document).ready(function() {
$("input[type='date']").change(function() {
console.log('got here');
toggleEmptyInputs($(this));
});
});
function toggleEmptyInputs(inputElement) {
var hasValue = !!inputElement.val();
inputElement.toggleClass("empty", !hasValue).toggleClass('colorme', hasValue);
inputElement.closest(".col").toggleClass("hidelabel", hasValue);
}
CSS:
input.colorme {
color: lime;
background-color: pink;
}
I have changed the
$(document).ready(function()
to
$(window).load(function ()

how to prevent dynamic span formation in JavaScript validation

I have a registration form, validation is done by JavaScript. If validation fails it will shows error in span attribute in dynamically bellow eachy field. But problem is that if the validation is true, the span is generated but not visible. So there is additional blank space after onchange. How can I solve this?
form.validate({
doNotHideMessage: false, //this option enables to show the error/success messages on tab switch.
errorElement: 'span', //default input error message container
errorClass: 'validate-inline', // default input error message class
focusInvalid: false, // do not focus the last invalid input
rules: {
birth_town: {
parentname: true,
required: true
},
birth_district: {
parentname: true,
required: true
},
},
messages: {
name: {
required: "select one ",
minlength: jQuery.format("select one")
}
},
});
Try display:none instead of visibility:hidden.
JSFiddle
Code
function hide() {
var err = document.getElementById("err1");
err.className = "hidden";
}
function invisible() {
var err = document.getElementById("err1");
err.className = "invisible";
}
(function() {
var val = document.getElementById("txt1").textContent;
if (val.length == 0) {
var err = document.getElementById("err1");
err.innerHTML = "Enter some text";
err.className = "invisible";
}
})()
.hidden {
visibility: hidden;
}
.invisible {
display: none
}
<input type="text" id="txt1">
<br/> <span class="error" id="err1"></span>
<input type="text" id="txt2">
<br/> <span class="error" id="err2"></span>
<button onclick="hide()">hidden</button>
<button onclick="invisible()">invisible</button>
I think that your problem is in CSS.
You probably set somewhere top or bottom (or both) margins for your validate-inline class. The Validate plugin attaches this class to both incorrectly filled input and following error span.
You can see it in this JS Fiddle.
Try to click 'Submit' with inputs empty. You will see error messages popping up. Then try to fill the first input. Error for that one hides but space remains. This is because the second input keeps class validate-inline and it is its margin that keeps the space not the hidden error span of the first input.
Try to remove margins from validate-inline class in your CSS and see if that helps.
PS. Also I'm not sure about parentname: true - didn't find this in plugin rules documentation and jsFiddle won't work with it so I removed them from rules.

Bootstrap select Plugin Not work With jQuery Validation

I design my HTML selectbox using bootstrap select plugin. Now, i add jQueryvalidation Plugin for validate my form But, Validation form not work with bootstrap select plugin.
DEMO HERE
HTML:
<form id="myform">
<select name="year" class="selectpicker">
<option value="">Year</option>
<option value="1">1955</option>
<option value="2">1956</option>
</select>
<br/>
<input type="submit" />
</form>
JS:
$(document).ready(function () {
$('select').selectpicker();
$('#myform').validate({ // initialize the plugin
rules: {
year: {
required: true,
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
NOTE: For check this conflict, remove Line 2 from JS, jQuery Validation Worked.
EDIT: adeneo Fix Problem Using ignore[] method : FIDDLE
$('#myform').validate({ // initialize the plugin
ignore: [],
rules: {
year: {
required: true
}
},
errorPlacement: function(error, element) {
if (element.attr("name") == "year") {
error.insertAfter(".bootstrap-select");
} else {
error.insertAfter(element);
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
Now This Worked but I have New Problem: In normal Validation after select fields, error message This field is required auto Hide( OR with add any css, show success message) but Now, error message is show after fix required field. in act: when we choose years, error message not hide.
How do fix This?
The select plugin hides the original select and creates a new one with an unordered list that updates the hidden selects value, but hidden elements are not validated by default by the validation plugin, you have to use the ignore rule and turn on validation for hidden elements
$('#myform').data("validator").settings.ignore = "";
FIDDLE
or
$('#myform').validate({ // initialize the plugin
ignore: [],
rules: {
year: {
required: true
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
FIDDLE
The Bootstrap select plugin creates a new dropdown from an unordered list, and the original select is hidden and it's value is updated when the user interacts with the unordered list.
This has the disadvantange of also moving the error message, as the original, now hidden select is the element being validated, and the new visible dropdown made up of an unordered list is inserted by Bootstrap below the original select in the DOM, the error message is inserted after the original select, but before the unordered list, so it appears above the custom dropdown, not below it like it would if the original select was used.
To fix it you can move the error message for any given element rather easily
$('#myform').validate({ // initialize the plugin
ignore: [],
rules: {
year: {
required: true
}
},
errorPlacement: function(error, element) {
if (element.attr("name") == "year") {
error.insertAfter(".bootstrap-select");
} else {
error.insertAfter(element);
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
FIDDLE
I had a similar issue so here's how I kind of extended #adeneo's answer together with lessons learnt from (the post here).
Note: For those who bump into this post, please read #adeneo's answer and
(the post here) to understand the scope of this solution.
The resulting code that very well functions flawlessly for me looks as follows:
jQuery / javascript:
$(document).ready(function() {
$.validator.setDefaults({
/*OBSERVATION (1): note the options used for "ignore"*/
ignore: ':not(select:hidden, input:visible, textarea:visible)',
/*...other options omitted to focus on the OP...*/
errorPlacement: function (error, element) {
/*OBSERVATION (2): note how selection is on the class "selectpicker"*/
if (element.hasClass('selectpicker')) {
error.insertAfter('.bootstrap-select');
} else {
error.insertAfter(element);
}
/*Add other (if...else...) conditions depending on your
* validation styling requirements*/
}
});
$('#myform').validate({
rules: {
'year': {
required: true
}
},
messages: {
'year': {
required: 'Please select a year from the dropdown'
}
}
});
});
HTML:
<form id="myform">
<select name="year" class="selectpicker">
<option value="">Year</option>
<option value="1">1955</option>
<option value="2">1956</option>
</select><br/>
<input type="submit" />
</form>
Explanation:
OBSERVATION (1): ignore: ':not(select:hidden, input:visible, textarea:visible)' simply means to ignore validation for all elements that's not a hidden <select>, that's not a visible <input> and that's not a visible <textarea>.
In simpler English, it just says to validate hidden <select>, ignore hidden <input> and ignore hidden <textarea> which is what we usually want in many cases. This I think is a better way to target what validation should be ignored or not.
Based on #Alvin Lee's answer here, setting the ignore options on the form element as follows was ok, but had its caveats;
$('#myform').validate().settings.ignore =
':not(select:hidden, input:visible, textarea:visible)';
The Problem: The bootstrap select element got validated but showed the default message This field is required on every other input element instead of overriding it with all the custom validation messages that were previously configured.
The fix: move the ignore setting into $.validator.setDefaults({...}) block... Voila! ! !
OBSERVATION (2):
Instead of doing if (element.attr("name") == "year") {...} like #adeneo pointed, I rather decided to select on class='selectpicker'... then in the javascript, check if the element had this class by doing if (element.hasClass('selectpicker')) {...}. This just ensures that this rule can be applied to all bootstrap-select elements as long as they're decorated with the class selectpicker.
Hope this is clear enough and helpful to somebody who has similar issues!
If you use 'selectpicker' class to initialize bootstrap-select widget, I recommend to partially solve the issue via changing default ignore settings for jquery validate:
$.validator.setDefaults({ ignore: ':hidden:not(.selectpicker)' });
before you validate your form. This is a bit better approach, and you also need to move error messages as adeneo supposed.
And still it will not have a similar validation behavior as select would have. The problem arise when the parent container is hidden. In case you do not use bootstrap-select your select will not validate when container is hidden, but when you use it still validates.

jQuery validation: hide error messages and change invalid fields background color

Here's a sample form.
How can I customize the form so it doesn't display any error messages and instead changes invalid fields background color?
Tried this to no avail:
$("form").validate({
errorPlacement: function(error, element) {
$(element.error).css("background","red");
}
})
All you need is two lines of CSS:
label.error {display: none !important;}
.error {background: #F00;}
You can do this by handling the invalidHandler callback in validate plugin:
Code:
$('#commentForm').validate({
invalidHandler: function() {
setTimeout(customizeErrors, 200);
}
});
function customizeErrors() {
$('label.error').each(function() {
$(this).prev().addClass('has-error');
$(this).prev().attr('title', $(this).text());
});
$('label.error').remove();
}
Demo: http://jsfiddle.net/2LwTa/
Note: The error message should ideally not be only a tooltip, as that would mean someone using just the keyboard will never see it.

Categories