While using the jQuery Validation plugin I'm trying to do a conditional validation on a text box. The rules for the text box are these: 1) required and needs to be within a range of 1-90 if the first radio button is marked. 2) if the second radio button is checked, the text box does not need to be considered.
So I've got the following code written for handing the required on the check of the first radio button:
$("#Form").validate({
rules: {
daysInputBox: {
required: {
depends: function () {
return $('input:radio[name=days]:checked');
},
messages: {
required: 'This field is required.'
}
}
}
}
});
Yet, when the code moves on to calling if the form is valid, I always get a true value back. Is there some black magic I'm missing here in making this validation work correctly?
have you tried making sure your depends function returns boolean value:
...
depends: function () {
return $('input:radio[name=days]:checked').length !== 0;
},
...
Related
I'm using webix as my JavaScript front end.
I've created a form with a colorpicker view. In Webix, by default, the colorpicker only allows users to pick from a pre-selected range of colors, and returns the hex code of the color selected.
This behavior can be overridden to allow entering of any color by using the option editable: true. However, editable: true allows users to enter anything into the colorpicker as if were a free text field.
I'm trying to use a custom validation to work around this. I should be able to return false in the custom validation function to alert the user user of an invalid value and to prevent the form from being saved until it's fixed. However, the custom validation function never gets called when used on the colorpicker.
Here's a webix snippet of what I'm trying:
https://snippet.webix.com/28oadxzl
webix.ui({
view:"form",
id: "theForm",
name: "theForm",
elements:[
{
view:"colorpicker",
label:"color",
name:"color",
id: "color",
editable: true,
validate: webix.rules.iscolor,
on: {
onChange: function(newv, oldv) {
// this gets called every time the color picker is changed.
webix.message({text: "onChange: " + newv})
this.validate();
}
}
},
{
view:"button",
type:"form",
value:"ok",
width:200,
align:"right",
click: function() {
// this gets called when the "ok" button is clicked.
webix.message({text: "click"});
$$("theForm").validate();
}
}
],
rules: {
iscolor: function(value) {
// never gets called! Should be called on colorpicker change and on "ok" click.
return false; // replace with regex hexcode validation.
webix.message({text: "iscolor: " + value})
}
}
});
You were almost right: https://snippet.webix.com/4mw3mxk8
The thing is that:
as a key in rules, you must use the name of the control ("color" in your case)
webix.rules includes only predefined validation rules (isEmail, isNotEmpty, etc)
can KendoUI grid enforce minlength validation. I have some troubles with it. Look at the screenshot.
I have set minlength and maxlength. It doesn't allow me to enter more than 10 letters, however, I can enter less than 2 letters and update the entry in grid.
Is this Kendo issue?
As mentioned in my comments, minlength doesn't work because that attribute doesn't exist in HTML5 whereas maxlength does.
Instead, you have to use custom validation, or use the pattern attribute.
Pattern Attribute
my_name {
validation: {
required: true,
pattern:'.{2,10}'
}
},
This means that my_name must be between 2 to 10 characters. It will allow you to type less or more, but will throw invalid message when you try to update.
Custom Validation:
my_name {
validation: {
required: true,
lengthRule: function (input) {
if (input.is("[name='DirectionName']") && input.val() !== "") {
input.attr("data-lengthRule-msg", "My Name must be between 2 to 10 characters.");
return (input.val().length<=10 && input.val().length>=2);
}
return true;
},
}
},
With the latter method, there is a known bug, so I am not to keen on using the latter method.
Custom Valiation Bug FYI: Validation is not always triggered when editing with backspace
I have a textbox where I need the text to become bullets after its validated. I am using jquery validation plugin to validate onfocusout. After the textbox is validated, if it is valid, I need the text to become asterisks or bullets (like a password textbox).
I can't just change the text to '*' because I need to keep the value of the textbox because otherwise, when the page validates again, it says it is invalid.
I don't want to have 2 different textboxes that are hidden/shown because it flashes in IE and looks very unprofessional and it also presents validation issues.
I can't change the 'type' of the textbox because that is not supported in IE.
Any other ideas? I searched a lot but have not come up with anything that works for me. Thanks!
Here is the code I have so far (following Eric's suggestion):
I have a textbox and a hidden field:
<asp:TextBox ID="txtProvId" runat="server"></asp:TextBox>
<asp:HiddenField ID="hdfProvId" runat="server"></asp:HiddenField>
The validation (on the hidden field):
$("form").validate(
{
onfocusout: function (element) {
jQuery(element).valid();
},
//error is placed in the textbox's tooltipster
errorPlacement: function (error, element) {
$(element).tooltipster('update', $(error).text());
$(element).tooltipster('show');
},
//tooltipster is removed when validation is passed
success: function (label, element) {
$(element).tooltipster('hide');
}
});
$('[id$="hdfProvId"]').each(function () {
$(this).rules('add', {
required: true,
number: true,
minlength: 7,
maxlength: 7
});
});
onFocusOut event on the textbox:
$('[id$="txtProvId"]').bind("focusout", function (event) {
$('[id$="hdfProvId"]').val($(this).val());
alert($('[id$="hdfProvId"]').val());
var isValid = $('[id$="hdfProvId"]').valid();
if (isValid == true) {
$(this).val('*******');
}
});
All this works great except that I don't know how to get the validation error to display. I am displaying the errors using jquery tooltipster plugin. It displays a tooltip next to each field with an error. When the validation is on the hidden field, no tooltip displays. I need it to display the tooltip on the textbox. Here is the tooltip code:
$('form input[type=text], input[type=password]').tooltipster({
trigger: 'custom',
onlyOne: false,
position: 'right'
});
The code to display it is above in the valiation code. Thanks for your help.
I added code to create a tooltip for hidden fields:
$('form input[type=text], input[type=password], input[type=hidden]').tooltipster({
trigger: 'custom',
onlyOne: false,
position: 'right'
});
The hidden field's tooltip was showing at the top of the page so I changed it to show on the previous element:
errorPlacement: function (error, element) {
if ($(element).prop('type') == 'hidden') {
$(element).prev().tooltipster('update', $(error).text());
$(element).prev().tooltipster('show');
}
else {
$(element).tooltipster('update', $(error).text());
$(element).tooltipster('show');
}
},
//tooltipster is removed when validation is passed
success: function (label, element) {
if ($(element).prop('type') == 'hidden') {
$(element).prev().tooltipster('hide');
}
else {
$(element).tooltipster('hide');
}
}
And now in all works!
Thanks all for you help in pointing me in the right direction.
I have more select menus, named menu1, menu2, menu3 etc...
All of them have values from 0 to 10. By default all are on 0.
How do I check with jquery validation plugin that at least one of the menus have a greater than zero value? Because each has a different name (I can give same class, but I do not see how this helps in validation plugin, because I can validate rules against form names not classes).
One solution is to create a custom rule.
I have adapted this answer and added a custom rule called mulitselect. This adds an error to the first dropdown list if none have a value > 0. Check the demo on jsfiddle.
note1 This currently is applied to every select list in the form, change the selector to limit it to certain select lists by class or otherwise.
note2 I added the onclick function after an invalid form has been submitted as adding it in the options resulted in validation that was a little too 'eager'.
js is as follows
$(function () {
$.validator.addMethod("multiselect", function (value, element) {
var countValid = $('select').filter(function () {
return $(this).val() > 0;
}).length;
if (countValid === 0 && $('select:first')[0] === element) {
return false;
}
else {
return true;
}
}, "please select at least one of the menus");
$('select').addClass("multiselect");
$('form').bind("invalid-form", function () {
$('form').validate().settings.onclick = function () { $("form").valid() };
}).validate({
debug: true
});
});
When I used datepicker with trigger icon so that users could choose date from clicking this icon or type directly in textbox (txtDate), I also used jquery validation to require textbox must be not empty.
But when a user submit the form with empty textbox (txtDate.Text=""), the error message of validation push trigger icon to the right. Could you tell me the solution? Thank you very much!
$('#some_form').validate({
rules: {...},
messages: {...},
errorPlacement: function(error, element) { //solve you problem
var trigger = element.next('.ui-datepicker-trigger');
error.insertAfter(trigger.length > 0 ? trigger : element);
}
});
The errorPlacement function receives two parameters - the error message and the validated element. Use the latter to decide whether or not to customize the placement for your fields (for example, by adding a class):
$('form').validate({
rules: {...},
errorPlacement: function(error, element) {
if (element.hasClass('customError')) {
// custom error placement
}
else {
element.after(error); // default error placement
}
}
});