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.
Related
I have a form
<form id="newRecord">
<input type="text" required/>
</form>
<button form="newRecord" type="submit">Submit</button>
http://codepen.io/anon/pen/EZwRjK
When the field is empty, and you click the button, you get a "Please fill out this field." pop up next to the field. Is there a way to detect if that pop up appears with JavaScript?
In HTML5, the pseudo-class :invalid is applied to any input that triggers the "This field is required" dialog box.
If you put the listener on your button, you could find out if the dialog box appeared or not by checking to see if there were any inputs marked :invalid...
$("#newRecord input[type=submit]").click(function() {
if ($("#newRecord input:invalid").length) {
//The popup appeared
} else {
//The popup did not appear
}
});
JSFiddle demo
In fact you can. You can use checkValidity() method. It returns true if the element contains a valid data.
$(function() {
$("#submit-button").click(function () {
// using jquery
console.log($("#input-text")[0].checkValidity());
// using javascript
var input = document.getElementById("input-text");
console.log(input.checkValidity());
});
});
Fiddle
Update
Seems the pop up is not showing when using type="button".
A work around I found is to use $("input").on("blur", function () { instead.
So it should be now:
$(function() {
$("input").on("blur", function () {
console.log($("#input-text")[0].checkValidity());
var input = document.getElementById("input-text");
console.log(input.checkValidity());
// checking as a whole
console.log("Form - ", $("#newRecord")[0].checkValidity());
});
});
Fiddle
REACT / NEXT.JS
In my case, it was because the 'input' tags were required and were not in the viewport (not visible) when submitting on my form.
The form was hidden when a useState was false const [isOpen, setIsOpen] = useState(false), then it was necessary to change the state to true so that the form would appear and the "fill these fields" message.
Solution was with onInvalid() property
<input onInvalid={() => setIsOpen(true)} type='radio' required />
I'm trying to build a server control that has a radiobuttonlist with 2 items and a textbox.
THe radio buttons are YES en NO options.
When YES is selected I want the textbox to be visible and it must be required to fill in.
On NO, the textbox becomes invisible.
I manages to get the textbox to appear and disappear based on the option choice.
But how do I add validation to the textbox and remove it when not visible?
I have tried it with the ASP validators, but the jquery doesn't disable them when the textbox is not visible.
I tried something like this, but it is not working:
<script type="text/javascript">
$(function()
{
$('#TravelOption2_rbList').change(function()
{
var index = $('#TravelOption2_rbList input[type=radio]:checked').val();
if (index != '0')
{
$('#TravelOption2_lblName2').css({'visibility':'visible'});
$('#TravelOption2_txtName1').css({'visibility':'visible'});
$('#TravelOption2_lblName3').css({'visibility':'visible'});
// create validator (not working)
$('#TravelOption2_txtName1').rules('add', {
required: true,
minlength: 2,
messages: { required: 'Required input', minlength: 'Please enter the cost.' }
});
} else {
$('#TravelOption2_lblName2').css({'visibility':'hidden'});
$('#TravelOption2_txtName1').css({'visibility':'hidden'});
$('#TravelOption2_lblName3').css({'visibility':'hidden'});
// remove the validator here
}
});
});
</script>
I have seen a lot of examples but they are not working for me.
Would it not be easier to simply check if the textbox has at least 2 characters in it when you submit it's contents? I'm assuming this is some sort of input form.
<script type="text/javascript">
$(function() {
$('#submitButton').on('click', function(){
if ($('#TravelOption2_txtName1').val().length > 1 ) {
//Textbox has at least 2 characters in it
}
})
});
</script>
This article helped me solve this problem.
Enable-Disable-ASPNet-Validator-Client-Side-Validation-using-JavaScript-or-jQuery
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.
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.
I'm trying to use the jQuery Validation plugin to make a multistep form with tabs, but I keep getting an "element is undefined" error when I attempt to loop through all the inputs. Any suggestions? I don't understand what's wrong. I've tried placing the checkbox in multiple places, and it seems to happen everywhere (i.e. not just at the 2nd last tab).
var tabs = $("#tabs").tabs({
disabled: [1,2,3,4,5],
select: function(event, ui) {
var valid = true;
var current = $(this).tabs("option", "selected");
var panelId = $("#tabs ul a").eq(current).attr("href");
$(panelId).find("input").each(function(index, element) {
if (!validator.element(this) && valid) {
if(ui.index > current) {
valid = false;
}
else
{
//re-disable the next tab
}
}
});
return valid;
}
});
$(".nexttab").click(function() {
var selected = $("#tabs").tabs("option", "selected");
$("#tabs").tabs("enable", selected+1);
$("#tabs").tabs("option", "selected", selected + 1);
});
HTML Part:
<div id="general">
</div>
<div id="problemtab">
<p>
<input type="checkbox" name"response" id="response" value="agree" class="required"><label for="response">I Agree</label>
</p>
<p>
<a class="prevtab navbutton"><span>Prev</span></a>
<a class="nexttab navbutton"><span>Next</span></a>
</p
</div>
<div id="lasttab">
</div>
Thanks for any help!
Edit:
It's giving me an error in jquery-validate.js:787
staticRules: function(element) {
var rules = {};
var validator = $.data(element.form, 'validator'); // <---- Error here
if (validator.settings.rules) {
rules = $.validator.normalizeRule(validator.settings.rules[element.name]) || {};
}
return rules;
},
Edit#2: element/this is defined as [object HTMLInputElement]
Here is my validator:
var validator = $("#myForm").validate({
ignore : ['#tabs .inactive input'], // tells the validator to only validate elements on your current tab
errorElement: "div",
wrapper: "div", // a wrapper around the error message
errorPlacement: function(error, element) {
if (element.parent().hasClass('group')){
element = element.parent();
}
offset = element.position();
error.insertBefore(element)
error.addClass('message'); // add a class to the wrapper
error.css('position', 'absolute');
error.css('left', offset.left + element.outerWidth());
error.css('top', offset.top);
}
});
You forgot an equal sign for the name attribute of your checkbox, so the name attribute is not set.
name"response" should be name="response"
I noticed yesterday that jquery.validate needs a name on elements to work, or it will throw this error.
Make sure you have just one form in your page. I used to have two forms in the same page and that was causing the problem you mention.
This error also might be related to this issue of JQuery with hidden chekcboxes (or radioboxes). This issue hasn't been addressed but it could be solved by setting (temporarily) validatorInstance.settings.ignore =''.
I faced that issue with checkboxes & hidden inputs on the form in MVC 5 Jquery 3.3.1, nothing worked so I had to disable the default validation and do some custom validation.
<button type="submit" id="btnSubmit" formnovalidate="formnovalidate" class="btn">Submit</button>
It started coming when I added
$.validator.methods.date = function (value, element) { .....