jquery form validate not catching blank sumbission - validation

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.

Related

Kendo grid Use previous filter values on relaod dosn't work

I'm trying to keep the filter value into KendoGrid and reuse it on relaod.
I find some code sample but doesn't working. I used getOptions to store values into localStorage. It's working. I have values into localStorage["kendo-grid-options"]. On reload, value appears into filters on header grid but data don't load. Error in the consoel is :
[! - SessionID: q0pbq0zsol3mjsxtd5mlendu, PageInstanceID: d11a8e2e-d716-43a0-8f4e-679eb87ad167, DateTime: 04/20/2022 20:53:10.894] Message: Uncaught
TypeError: Cannot read properties of undefined (reading 'data')
Impossible to find solution. If somebody has en idea... :)
My code is the following
function LoadSampleQualityControlPlanGridSummary(control,params) {
control.dataSource = new kendo.data.DataSource({ transport: {
read: function (options) {
GetDsBySp("sp_HMI_GetSampleControlPlanList", params, options.success);} }, schema: { model: {
id: "qm_spec_id" }, fields: {
qm_spec_desc: {
type: "string"
},
plan_name: {
type: "string"
} } } }); }
function InitSampleQualityControlPlanSummaryGrid(control) {
control.columns = [ { field: "qm_spec_name", title:
"Name") }, { field: "qm_spec_desc", title: "description")
}, { field: "plan_name", title: "Plan", } ]; }
//On load
_controls.SampleControlPlanSummary = control.findByXmlNode("GSQCP");
_controls.$SampleControlPlanSummary = $(_controls.SampleControlPlanSummary.domElement).data("kendoGrid");
InitSampleQualityControlPlanSummaryGrid(_controls.SampleControlPlanSummary);
var options = localStorage["kendo-grid-options"];
if (options) {
var parsedOptions = JSON.parse(options);
_controls.$SampleControlPlanSummary.setOptions(parsedOptions); _controls.$SampleControlPlanSummary.setDataSource(gridData);
} LoadSampleQualityControlPlanGridSummary(_controls.SampleControlPlanSummary,
paramControl);

KendoGrid - After applying custom filter and then navigating to next or any other page, the filter values are not getting passed to controller

Used Kendo Version: 2015.2.624
I have implemented kendogrid server side paging with additional parameters. Below is how my controller looks like:
public ActionResult GetData([DataSourceRequest] DataSourceRequest request, DateTime startDate, DateTime endDate, int state = -1, string poolName = null, string submitter = null)
{
poolName = string.IsNullOrEmpty(poolName) ? null : poolName;
submitter = string.IsNullOrEmpty(submitter) ? null : submitter;
var summarylist = new List<Summary>();
var total = 0;
using (var db = new SummaryEntities())
{
var jobs = db.SummaryTable.Where(k => k.created >= startDate && k.created <= endDate)
.Where(k => state != -1 ? k.state == state : k.state > state)
.Where(k => poolName != null ? k.pool_name == poolName : k.pool_name != null)
.Where(k => submitter != null ? k.submitter == submitter : k.submitter != null);
jobs = jobs.OrderByDescending(job => job.id);
total = jobs.Count();
// Apply paging...
if (request.Page > 0)
{
jobs = jobs.Skip((request.Page - 1) * request.PageSize);
}
jobs = jobs.Take(request.PageSize);
foreach (var job in jobs)
{
summarylist.Add(new Summary(job));
}
}
var result = new DataSourceResult()
{
Data = summarylist,
Total = total
};
return Json(result, JsonRequestBehavior.AllowGet);
}
additional parameters are the current values which the user has set over the widget datepicker, input box etc.
Below is how my datasource looks like in grid:
<script type="text/javascript">
j$ = jQuery.noConflict();
j$(document).ready(function () {
j$("#grid").kendoGrid({
dataSource: {
transport: {
read: {
url: "/Home/GetData/",
dataType: "json",
data: {
startDate: j$("#startdate").val(),
endDate: j$("#enddate").val()
}
}
},
pageSize: 30,
serverPaging: true,
schema: {
data: 'Data',
total: 'Total'
}
},
height: j$(window).height() - 85,
groupable: true,
sortable: true,
filterable: false,
columnMenu: true,
pageable: true,
columns: [
{ field: "JobId", title: "Job Id", template: '#:JobId#', type: "number" },
{ field: "Name", title: "Job Name", hidden: true },
{ field: "PoolName", title: "Pool Name" },
{ title: "Date Time", columns: [{ field: "Start", title: "Start" },
{ field: "End", title: "End" }
],
headerAttributes: {
"class": "table-header-cell",
style: "text-align: center"
}
},
{ field: "State", title: "State" },
{
title: "Result", columns: [{ field: "ResultPassed", title: "P" },
{ field: "ResultFailed", title: "F" }
],
headerAttributes: {
"class": "table-header-cell",
style: "text-align: center"
}
},
{ field: "Submitter", title: "Submitter" }
]
});
});
</script>
It works pretty good until I observed this issue:
Change the filter values i.e submitter, date range etc and
controller gets all this information in additional parameters where
I am taking action accordingly and it works just fine.
Now suppose the result returned from step 1 has multiple pages and
when you click next page, or last page or any other page number, the
controller gets invoked which is expected but the additional
parameters being set in step 1 is not getting passed again instead
the default values are there which is ruining everything.
Correction:
Additional parameters are getting lost at client side only.
Now please tell me what am I missing here?
Expected Result: In step 2 additional parameters should not get lost and it should be same as step 1.
Any help is appreciated.
EDITED:
Complete controller and grid code.
Thanks,
Vineet
I got the solution from telerik support team:
Reply:
The described undesired behavior can be caused by the fact that the additional parameters:
data: {
startDate: j$("#startdate").val(),
endDate: j$("#enddate").val()
}
... are set to objects, instead of a functions. If they are set as functions, the values of the corresponding inputs will be evaluated every time read() is called, and the current values will be passed (like shown in the second example in the API reference):
http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#configuration-transport.read.data

Kendo UI Grid inline edit define custom values for min validation

I am using Kendo grid and want to validate one field's min value by another field from same record.
Meaning my data is like this :-
var courses = [{
CourseID : 1,
CourseName : "iPhone",
MinAge: 12,
MaxAge : 22,
MinAgeThreshold : 10,
MaxAgeThreshold : 30,
StartDate: "12/10/2014",
},
{
CourseID : 2,
CourseName : "Android",
MinAge: 12,
MaxAge : 22,
MinAgeThreshold : 10,
MaxAgeThreshold : 30,
StartDate: "12/10/2014",
}]
and I want to use MinAgeThreshold value in MinAge's validation min value, something like this:-
schema: {
model: {
id: "CourseID",
fields: {
CourseID: { editable: false, nullable: true },
StartDate: { editable: false, nullable: true },
CourseName: { editable: false, nullable: true },
MinAgeThreshold: { editable: false, nullable: true },
MinAge: { type: "number", validation: { required: true, min: MinAgeThreshold} },
MaxAge: { type: "number", validation: { required: true, min: 1} },
}
Is this possible somehow?
I tried to use in validation custom function like this
MinAge: {
type: "number",
validation: {
required: true,
minagevalidation: function (input) {
}
},
but I was not able to retrieve the values of MinAgeThreshold in minagevalidation function.
Any help would be greatly appreciated.
Regards
you can try something like given below to give the custom validation message and force the user to set value greater than the minimum value based on other input field in the same kendo grid.
MinAge: { type: "number",
validation: {
required: true,
MinAgevalidation: function (input) {
if(input.is("[name='MinAge']") &&(parseInt($("input[type='text'][name='MinAge']").val()) < parseInt($("input[type='text'][name='UnitPrice']").val()))){
input.attr("data-MinAgevalidation-msg", "MinAge should greater than MinAge threshold");
return false;
}
return true;
}
sample jsfiddle to set minimum value of one field based on other field's value .
I think I might have a solution for that kind of a problem. If you want to set the max of a field by the value of a different field you can add that to the grid edit method of your kendogrid.
var grid = $("#grid").kendoGrid({
edit: function(e){
if ( e.container.find("input[data-find='value:MinAge']).length != 0 ){
var numericTextBox = e.container.find("input[data-find='value:MinAge']).data("kendoNumericTextBox");
numericTextBox.min(e.model.MinAgeThreshold);
}
}
});
This will set the numerictTextBox of the MinAge input to min of the MinAgeThreshold that is in the dataItem of the row (model). That works with step, max, and so on as well. Edit is triggered when you enter the field. So if the initial value is 0 and your MinAgeThreshold is something else it will then switch to the MinAgeThreshold.

Signature Pad Validation

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.

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