jQuery Validate - Group Fields not working properly when grouping multiple fields - jquery-validate

The below code works but for DOB, it displays the error message after the first text box (DayOfBirth) instead of the third one (YearOfBirth).
$("form").validate({
rules: {
DayOfBirth: { required: true },
MonthOfBirth: { required: true },
YearOfBirth: { required: true },
SSN1: { required: true },
SSN2: { required: true },
SSN3: { required: true }
},
groups: {
DateofBirth: "DayOfBirth MonthOfBirth YearOfBirth",
SSN: "SSN1 SSN2 SSN3"
},
errorPlacement: function(error, element) {
if (element.attr("name") == "DayOfBirth" || element.attr("name") == "MonthOfBirth" || element.attr("name") == "YearOfBirth")
error.insertAfter("#YearOfBirth");
else
error.insertAfter(element);
if (element.attr("name") == "SSN1" || element.attr("name") == "SSN2" || element.attr("name") == "SSN3")
error.insertAfter("#SSN3Text");
else
error.insertAfter(element);
}
});

Change...
error.insertAfter("#YearOfBirth");
to...
form.find(".error").append(error);
and the error will display after the YearOfBirth.
Next time, perhaps the whole code with the HTML or a jsFiddle demostration of your problem would help explain your question more clearly.

Related

Kendo Grid Custom Toolbar button Enable/Disable

I have a kendo grid with save button in the Tool bar panel. I have a proposed discount column which is editable and if the user enters whole numbers between 0 and 100(excluding decimals) , the save button should be visible or enabled otherwise invisible or disabled. I was able to achieve making the button invisible or disable but when they enter correct value, the button was not getting visible or enabled. Please help me. I just started working on Kendo UI recently.
function setEnabled(enabled) {
if (enabled) {
// $(".k-grid-nstToolbarBtn").removeClass("k-state-disabled");
$(".k-grid-nstToolbarBtn").show();
}
else {
// $(".k-grid-nstToolbarBtn").addClass("k-state-disabled");
$(".k-grid-nstToolbarBtn").removeAttr("href");
$(".k-grid-nstToolbarBtn").hide();
}
}
$('#NSTGrid').kendoGrid({
toolbar: [{ type: "button", text: "Save", name: "nstToolbarBtn", className: "k-grid-saveData" }],
dataSource: {
data: data.ReportData,
schema: {
model: {
fields: {
ProposedDiscount: {
validation: {
required: true,
proposeddiscountvalidationcvalidation: function (input) {
if (input.val() != "" && input.is("[name='ProposedDiscount']")) {
input.attr("data-proposeddiscountvalidationcvalidation-msg", "Proposed Discount should be whole number");
setEnabled(false);
return input.val() >= 0 && input.val() < 101 && input.val() % 1 == 0;
} else {
setEnabled(true);
return true;
}
}
}
},
ProductApprovedDiscount: { type: "decimal", editable: false },
BAN: { type: "string", editable: false },
I think the value passed to your setEnabled function needs to be the same as what you return as the validation result. Please try the following change:
proposeddiscountvalidationcvalidation: function (input) {
if (input.val() != "" && input.is("[name='ProposedDiscount']")) {
input.attr("data-proposeddiscountvalidationcvalidation-msg", "Proposed Discount should be whole number");
var valid = input.val() >= 0 && input.val() < 101 && input.val() % 1 == 0;
setEnabled(valid);
return valid;
} else {
return true;
}
}

Alphanumeric Sort in jqxGrid

I am using jQWidgets v3.7.1 and trying to sort columns in jqxGrid with a unique alphanumeric naming convention, “Foo-1,” “Foo-2″ etc., that I'm trying to sort by the last integer in the string, but because there are both alphabetic and numeric data in the string, the closest we can get is a sort that goes something like:
Foo-1
Foo-10
Foo-11
Foo-2
Foo-3
etc.
I know there are custom sorting abilities for the grid, but it’s not clear to me how to accomplish this sorting challenge that way. We really do not want to change our data structure to something like “Foo-01″, “Foo-02″ if at all possible. Thanks for any help you might be able to provide.
UPDATE: FYI, I have tried a variation of the custom sorting example provided by jqWidgets:
// prepare the data
var dataFields =
[
{ name: 'session_name', type: 'string' },
{ name: 'current_phase', type: 'string' },
{ name: 'current_stage', type: 'string' },
{ name: 'contractor_last_name', type: 'string' },
{ name: 'contractor_first_name', type: 'string' },
{ name: 'contractor_email', type: 'string' },
{ name: 'contractor_company_name', type: 'string' },
{ name: 'engagement_manager_last_name', type: 'string' },
{ name: 'engagement_manager_first_name', type: 'string' },
{ name: 'engagement_manager_email', type: 'string' },
{ name: 'department', type: 'string' },
{ name: 'start_time', type: 'date' },
{ name: 'outcome', type: 'string' },
{ name: 'outcome_report_file_name', type: 'string' },
{ name: 'end_time', type: 'date' },
{ name: 'jurisdictions', type: 'string' },
{ name: 'nls_session_id', type: 'string' },
{ name: 'next_steps_url', type: 'string' },
{ name: 'action_taken', type: 'string' },
];
var customsortfunc = function (column, direction) {
var sortdata = new Array();
if (direction == 'ascending') direction = true;
if (direction == 'descending') direction = false;
if (direction != null) {
for (i = 0; i < dataFields.length; i++) {
sortdata.push(dataFields[i]);
}
}
else sortdata = dataFields;
var tmpToString = Object.prototype.toString;
Object.prototype.toString = (typeof column == "function") ? column : function () { return this[column] };
if (direction != null) {
sortdata.sort(compare);
if (!direction) {
sortdata.reverse();
}
}
source.localdata = sortdata;
$("#evaluations-grid").jqxGrid('updatebounddata', 'sort');
Object.prototype.toString = tmpToString;
}
var compare = function (value1, value2) {
value1 = String(value1).toLowerCase();
value2 = String(value2).toLowerCase();
try {
var tmpvalue1 = parseFloat(value1.replace(/Foo\-/, ''));
if (isNaN(tmpvalue1)) {
if (value1 < value2) { return -1; }
if (value1 > value2) { return 1; }
}
else {
var tmpvalue2 = parseFloat(value2.replace(/Foo\-/, ''));
if (tmpvalue1 < tmpvalue2) { return -1; }
if (tmpvalue1 > tmpvalue2) { return 1; }
}
}
catch (error) {
var er = error;
}
return 0;
};
var source =
{
datatype: "json",
datafields: dataFields,
id: 'session_name',
url: url,
sort: customsortfunc,
sortcolumn: 'session_name',
sortdirection: 'asc'
};
but this not only gives me an even more incorrect series of results, viz.:
Foo-2
Foo-3
Foo-4
Foo-5
Foo-1
Foo-6
Foo-7
etc.
but if I try to change the sorting direction, I go from 11 results to 19, except the data is completely gone.
You can use custom compare function by replacing Foo- part (or all non digit characters), something like (taken from jqxgrid customsort example):
var compare = function (value1, value2) {
value1 = String(value1).toLowerCase();
value2 = String(value2).toLowerCase();
try {
var tmpvalue1 = parseFloat(value1.replace(/Foo\-/, ''));
if (isNaN(tmpvalue1)) {
if (value1 < value2) { return -1; }
if (value1 > value2) { return 1; }
}
else {
var tmpvalue2 = parseFloat(value2.replace(/Foo\-/, ''));
if (tmpvalue1 < tmpvalue2) { return -1; }
if (tmpvalue1 > tmpvalue2) { return 1; }
}
}
catch (error) {
var er = error;
}
return 0;
};

jquery form validate not catching blank sumbission

I can submit my form whether it is blank or partially filled in, this shouldn't happen since I'm using the jquery validator plug in. I have the plug in script in the right place and the validate method is properly attached to the right form selector. What else could be the problem?
$("form").submit(function(){
(".selector").validate({
rules: {
performance : {
required: true,
customvalidation: true
},
location : {
required: true,
customvalidation: true
},
date : {
required: true,
customvalidation: false
},
time : {
required: true,
customvalidation: true
},
guests : {
required: true,
customvalidation: true
},
price : {
required: true,
customvalidation: true
}
},
messages: {
performance : {
required: "enter a show name"
},
location : {
required: "enter a location"
},
date : {
required: "pick a date"
},
time : {
required: "give a time"
},
guests : {
required: "how many people do you need?"
},
price : {
required: "what is the cover price?"
}
},
submitHandler: function(form) {
console.log("now validated");
}
}); //closes validate
$.validator.addMethod("customvalidation",
function(value, element) {
return (/^[A-Za-z\d=#$%#_ \-]+$/.test(value));
},
"Sorry, no special characters allowed"
);
var date = $("#date").val();
var showName = $("#performance").val();
var venue = $("#location").val();
var time = $("#time").val();
var guests = $("#guests").val();
var price = $("#price").val();
//this is where I submit to my database//
});//closes submit
Modify your submit function to run event.preventDefault() if validation fails.
Normally you can use return false, but since you've added this event using a jQuery event, you have to use event.preventDefault() instead as discussed here at stackoverflow.

jQuery validate and groups - how to avoid errorPlacement usage?

Current example of groups usage says that errorPlacement should be defined, where names of fields are hard coded:
$("#myform").validate({
groups: {
username: "fname lname"
},
errorPlacement: function(error, element) {
if (element.attr("name") == "fname"
|| element.attr("name") == "lname" )
error.insertAfter("#lastname");
else
error.insertAfter(element);
},
debug:true
})
Is there any way to get rid of this errorPlacement with field names? The error message should be always places after last element in the group.
I think you're going to have to use errorPlacement, but you can pull out a few tricks to get the error in a consistent place among groups every time:
$("#test-form").validate({
groups: {
username: "fname lname",
range: "min max"
},
errorPlacement: function ($error, $element) {
var elementName = $element.attr("name"),
lastInGroup = $.map(this.groups, function(fields, name) {
var fieldsArr;
if (fields.indexOf(elementName) >= 0) {
fieldsArr = fields.split(" ");
return fieldsArr[fieldsArr.length - 1];
} else {
return null;
}
})[0];
if (lastInGroup) {
$error.insertAfter($("input[name='" + lastInGroup + "']"));
} else {
$error.insertAfter($element);
}
}
});
Basically, access the groups object that you've defined and find the last field in every group. Attach the error after that field.
Example: http://jsbin.com/acenic/

JQuery validate plugin(bassistance) dependency with selectbox

I have a select box and an input text. The input text is hidden by default. If I select "Other" in select box, the input text will show.
Here I want to apply the dependency validation. If the the selected text is "Other", then the input text should be required. My code shown below:
$(document).ready(function () {
$("#customer-registration").validate({
rules: {
province: {
required: true
},
otherState: {
maxlength: 100,
required: function (element) {
return $('#province option:selected').text() == 'Other';
}
}
},
messages: {
province: {
required: "Please select Province"
},
otherState: {
required: "Please enter other Province"
}
}
});
$("#submitFormBtn").click(function () {
if ($("#customer-registration").valid()) {
$("#customer-registration").submit();
}
});
$("#province").change(function(){
($(this).val() == "Other")? $("#otherState").show() : $("#otherState").hide();
});
});
When I select "Other", validation is happening properly. But when I select some other value in the selectbox, the error "Please enter other Province" still showing. Help me please...thanks in advance..
Hi you need to add something like this
otherState:{
required:{
depends: function(element){
return $('#province option:selected').text() == 'Other';
}
}
}

Resources