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';
}
}
}
Related
I have a working example of replacing Validation methods based on a dropdown's selection.
The issue I'm having is using a regex with the JQueryValidation, entering a valid Twitter address always returns the Invalid Address error.
The below function runs when the Page loads, I set the Default Validation, then I add new validation when the dropdown is changed.
jsFiddle - here
ValidationDefaults();
//Setup all .Select2
$(".select2").select2({
theme: 'bootstrap4',
placeholder: '- Search -',
});
$('#SocialMediaNetworkId').on('select2:select', function(e) {
var data = e.params.data;
AccountNameLabel(data.id);
});
$('#btnSubmit').on('click', function(e) {
if ($("form").valid()) {
/* $('#Edit').submit();*/
}
});
function AccountNameLabel(SocialMediaNetworkId) {
$("#Edit").data('validator').resetForm();
switch (parseInt(SocialMediaNetworkId)) {
case 1:
$("label[for='SocialMediaAccountName']").text("FaceBook Url");
$("#SocialMediaAccountName").attr("placeholder", "FaceBook Url - Ex. https://www.FaceBook.com/joeblow");
FaceBookValidation();
break;
case 2:
$("label[for='SocialMediaAccountName']").text("YouTube Url");
$("#SocialMediaAccountName").attr("placeholder", "YouTube Url - Ex. https://www.YouTube.com/joeblow");
YouTubeValidation();
break;
case 3:
$("label[for='SocialMediaAccountName']").html("Twitter Url");
$("#SocialMediaAccountName").attr("placeholder", "Twitter Url - Ex. https://www.twitter.com/joeblow");
TwitterValidation();
break;
case 4:
$("label[for='SocialMediaAccountName']").text("Instagram Url");
$("#SocialMediaAccountName").attr("placeholder", "Instagram Url - Ex. https://www.Instagram.com/joeblow");
InstagramValidation();
break;
}
}
function ValidationDefaults() {
$('#Edit').validate({
rules: {
SocialMediaNetworkId: {
required: true
}
},
messages: {
SocialMediaNetworkId: "* Required Field"
},
errorElement: 'span',
errorPlacement: function(error, element) {
error.addClass('invalid-feedback');
element.closest('.form-group').append(error);
},
highlight: function(element, errorClass, validClass) {
$(element).addClass('is-invalid');
},
unhighlight: function(element, errorClass, validClass) {
$(element).removeClass('is-invalid');
}
});
}
function TwitterValidation() {
var settings = $('#Edit').validate().settings;
$("#SocialMediaAccountName").rules("remove");
$("#SocialMediaAccountName").rules("add",
{
required: true,
pattern: "/http(?:s)?:\/\/(?:www\.)?twitter\.com\/([a-zA-Z0-9_]+)/",
messages: {
required: "Required input",
pattern: "* Must be a valid Twitter URL - Ex. https://www.twitter.com/joeblow"
}
}
);
//$("#SocialMediaAccountName").rules("add", {
// required: true,
// pattern: {
// required: "/http(?:s)?:\/\/(?:www\.)?twitter\.com\/([a-zA-Z0-9_]+)/"
// },
// messages: {
// required: "Required input",
// pattern: "* Must be a valid Twitter URL - Ex. https://www.twitter.com/joeblow"
// }
//});
//// Modify validation settings
//$.extend(true, settings, {
// rules: {
// // Add validation
// "SocialMediaAccountName": {
// required: true,
// pattern: "/http(?:s)?:\/\/(?:www\.)?twitter\.com\/([a-zA-Z0-9_]+)/"
// }
// }
//});
//$.extend(jQuery.validator.messages, {
// required: "* Required Field.",
// pattern: "* Must be a valid Twitter URL - Ex. https://www.twitter.com/joeblow"
//});
}
Client-side Generated KendoUI Grid is not highlighting selected row when grid is redisplayed (Kendo UI Complete v2013.1.514).
Kendoui grid is in a KendoUI Tab (Tab #1). Clicking on the 3rd row highlights the row. Clicking on the second tab (Tab #2) hides the grid tab and shows another grid. When clicking back on Tab #1 the first grid is redisplayed and the contents are shown.
When stepping through the tab onActivate(arg) function I can see using grid.select() that the row that was last selected is still the selected row however the row isn't highlighted.
I tried the following code in an attempt to reselect the row:
var element = $(WORK_PRODUCT),
grid = element.data("kendoGrid"),
row = element.find("tbody>tr[data-uid='" + grid.dataSource.get(_selectedWorkProduct).uid + "']");
grid.select(row);
I also examined the inner and outer HTML and the selected row matches exactly what was selected the first time the row was selected (TR class=k-state-selected role=row aria-selected=true data-uid="119b95c7-f3e4-4160-821e-507fbdc70026">7964
How can I visibly show that the row is selected? Thanks in advance!
Below is the code that initializes the grid:
DashViewUI.prototype.initWorkProducts = function (arg) {
$(WORK_PRODUCT).kendoGrid({
filterable: true
, sortable: true
, selectable: "row"
, pageable: true
, ajax: true
, columns:
[
{
field: "ID"
, title: ""
, sortable: true
, hidden: true
}
, {
field: "Number"
, title: "Case No."
, width: 80
, sortable: true
, filterable: true
}
, {
field: "Name"
, title: "Case Name"
, width: 120
, sortable: true
}
, {
field: "Status"
, title: "Status"
, width: 70
, sortable: true
}
]
, dataSource:
{
transport:
{
read:
{
url: AppPath + '/DashB/GetWorkProducts'
, contentType: 'application/json; charset=utf-8'
, type: 'GET'
, dataType: 'json'
}
}
, schema: {
model: {
id: "ID"
, fields: {
"ID": { type: "number" }
, "Number": { type: "string" }
, "Name": { type: "string" }
, "Status": { type: "string" }
}
}
}
}
, dataBound: function onDataBound(e) {
//alert('Data bound fired');
}
, change: function onCaseGridChange(arg) {
if (DEBUG)
debugger;
var cells = this.select();
var name = null;
if (cells.length > 0)
name = this.dataItem(cells[0]);
if (name.ID != null) {
// store the currently selected work product
_selectedWorkProduct = name.ID;
// refresh the party dial gauge
_dashViewUI.refreshDialGauge(PARTY_GAUGE, AppPath + '/DashB/GetCaseChildrenCount');
// reload the tasks for the selected work product
$(TASKS).data().kendoGrid.dataSource.read({ workProductID: _selectedWorkProduct });
}
}
});
};
The selected grid row will not be retained if you reload the grid. You have to store it before hand.
var selectedDataItem = grid.dataSource.getByUid(grid.select().data("uid"));
grid.dataSource.read();
if (selectedDataItem) {
var uid = grid.dataSource.get(selectedDataItem.id).uid;
grid.select('tr[data-uid="' + uid + '"]');
}
Here is a live demo: http://jsbin.com/USahiPor/1/edit
I need to access the column name dynamically in Kendo Grid template.
Code:
$("#grid").kendoGrid({
dataSource: [
{ Quantity: 2 , Amount: 650},
{ Quantity: 0, Amount: 0 },
{ Quantity: 1, Amount: 500 },
{ Quantity: 4, Amount: 1047 }
],
sortable: true,
columns: [
{
field: "Quantity",
template: function (dataItem) {
if (dataItem.Quantity == '0') {
return "--";
} else {
return dataItem.Quantity;
}
}
},
{
field: "Amount",
template: function (dataItem) {
if (dataItem.Amount == '0') {
return "--";
} else {
return dataItem.Amount;
}
}
}
]
});
Here inside the "columns -> template", I need to access the column thru variable instead of hardcoding it. How can I do that? Because in real life I will be having dynamic columns populated into dataSource and I will construct the columns array inside the for loop. Please help.
Please access this JSBIN: http://jsbin.com/egoneWe/1/edit
From what I understand, you build the columns array using something like:
var Definition = [
{ field: "Quantity" },
{ field: "Amount" }
];
var columns = [];
$.each(Definition, function (idx, item) {
columns.push({
field : item.field,
template: function (dataItem) {
...;
}
})
});
$("#grid").kendoGrid({
dataSource: data,
sortable : true,
columns : columns
});
Right? And the problem is that you want to use the same template function for several (all) columns instead of having to rewrite many.
If so, what you can do is:
var Definition = [
{ field: "Quantity" },
{ field: "Amount" }
];
var columns = [];
$.each(Definition, function (idx, item) {
columns.push({
field : item.field,
template: function (dataItem) {
return commonTemplateFunction(dataItem, item.field);
}
})
});
What I use in the columns array (columns definition for the Grid) is a function that receives two arguments: the dataItem for the row and the field's name being edited.
Then, I define the template function as:
function commonTemplateFunction(dataItem, field) {
if (dataItem[field] == '0') {
return "--";
} else {
return dataItem[field];
}
}
And your modified code is here : http://jsbin.com/egoneWe/3/edit
So, despite I cannot guess the column name, I can do the trick using the columns initiator.
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.
I have a multipage form using jqm. The last two pages uses Thomas j bradleys signature pad. I use jquery validate plugin to validate each page before it moves on.
I can not get jquery validate plugin to verify if the is a signature.
This is the code I use for the validation. All this works fine just need to add the signature validation in.
$("#breakinform").validate({
rules: {
sitename: {
required: true,
},
Address: {
required: true,
},
BreakInDate: {
required: true,
},
recafcheckbox: {
required: true,
},
sigPad: {
required: true,
},
},
messages: {
sitename: {
required: "Please Enter Site Name",
},
Address: {
required: "Please Enter Address",
},
BreakInDate: {
required: "Please Enter Date",
},
recafcheckbox: {
required: "Please Confirm",
},
sigPad: {
required: "Please Sign In The Box",
},
}
});
//break
$("a.check").click(function(){
if($("#breakinform").valid()){
} else {
navigator.notification.alert(
"Please Fill In The Required Fields!",
callBackFunctionB, // Specify a function to be called
'Missing Data',
"OK"
);
function callBackFunctionB(){
console.log('ok');
}
return false;
}
});
A workaround that I used by adding the following to my "submitHandler":
var result = true;
if ($('.sigPad input.output').length)
{
$('.sigPad input.output').each(function(){
if ($(this).val().length == 0) result = false; });
}
if (!result ) return false;
and keeping signaturePad's "validateFields" option to true.
#Hunty3000, I don't think you'll be able to use the jQuery validate plugin to validate your canvas so why not use Signature Pad's built in validation?
Here's how:
http://thomasjbradley.ca/lab/signature-pad/#accept-form
If you need more assistance, don't hesitate to ask.