When I add remote to Jquery Validate form submits when invalid - ajax

When I add remote to the jquery validate my form submits even if there are errors, when I remove remote it works properly and you can't submit the form and unless you have filled in all fields? Any ideas? code is below
<script>
$(document).ready(function () {
$("#SignUp").validate({
onsubmit: true,
onkeyup: function(element) { $(element).valid(); },
rules: {
email: {
required: true,
email: true
},
password: {
required: true,
password: true
},
confirm_password: {
equalTo: "#password",
required: true
},
company: {
nls:true,
required: true
},
telephone: {
required: true,
phoneUK: true
},
email2: {
email: true
},
website: {
url: true
},
address1: {
nls:true
},
address2: {
nls:true
},
town: {
nls:true
},
postcode: {
postcodeUK:true
},
country: {
selectcountry:true
},
terms:{
required:true
},
answer:{
remote: "Captcha/check-captcha.php",
type: "POST",
data: {
captcha: function() {
return $("#answer").val();
}
}
}
},
messages:{
email:
{
required: "Please Enter an Email Address"
},
password:
{
required: "Please Enter a Password"
},
confirm_password:
{
required: "Please Confirm Your Password"
},
company:
{
required: "Please Enter Your Company/Climbing Gym Name"
},
telephone:
{
required: "Please Enter a Telephone Number"
},
terms:
{
required: "Please Agree Our Terms and Conditions"
},
answer:{
remote: "You Have Entered The Captcha Correctly When This Message Disappears"
}
}
});
$.validator.addMethod("password", function (value, element) {
return this.optional(element) || /^[A-Za-z0-9!##$%^&*()_]{6,16}$/i.test(value);
}, "Passwords are 6-16 characters");
$.validator.addMethod("nls", function(value, element)
{
return this.optional(element) || /^[a-zA-Z0-9\s.\-_']+$/i.test(value);
}, "Please Only Enter Alpha Numeric Characters and Spaces");
jQuery.validator.addMethod('selectcountry', function (value) {
return (value != 'Nothing');
}, "Please Select a Country");
$.validator.addMethod("url", function(value, element)
{
return this.optional(element) || /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/i.test(value);
}, "Please Enter A Valid Website URL");
});
</script>
PHP is below:
<?php
session_start();
if(strtolower($_REQUEST['answer']) == $_SESSION['captcha']){
echo 'true';die;
}else{
echo 'false';die;
}
?>
The validation still works onkeyup etc with and without remote but just not on submit?

The remote rule syntax is slightly off in your case
answer: {
required: true,
remote: {
url: "Captcha/check-captcha.php",
type: "POST",
data: {
captcha: function () {
return $("#answer").val();
}
}
}
}

Related

Lightbox Not Working with jQuery

I have a problem with lightbox after loading the following script in my page:
jQuery.validator.addMethod('answercheck', function (value, element) {
return this.optional(element) || /^\b5\b$/.test(value);
}, "please type the correct answer (this is anti-spam)");
// validate contact form
$(function() {
$('#contact').validate({
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
answer: {
required: true,
answercheck: true
}
},
messages: {
name: {
required: "please enter your name",
minlength: "your name must consist of at least 2 characters"
},
email: {
required: "please enter your email address"
},
answer: {
required: "sorry, wrong answer! (this is anti-spam)"
}
},
submitHandler: function(form) {
$(form).ajaxSubmit({
type:"POST",
data: $(form).serialize(),
url:"process.php",
success: function() {
$('#contact :input').attr('disabled', 'disabled');
$('#contact').fadeTo( "slow", 0.15, function() {
$(this).find(':input').attr('disabled', 'disabled');
$(this).find('label').css('cursor','default');
$('#success').fadeIn();
});
},
error: function() {
$('#contact').fadeTo( "slow", 0.15, function() {
$('#error').fadeIn();
});
}
});
}
});
});
I have read about .live() and read this page http://api.jquery.com/live/ but I am a newbie and have trouble implementing it in my script. Any help please?
thank you

Kendo UI Inline Grid

I am having an issue with validation on certain fields. I want to only validate on a couple of fields, and the other fields should not validate. In my Email field, I am firing a function to check proper formatting, but the other fields are simply set to validate. Any help would be greatly appreciated.
model: {
id: "UserID",
fields: {
UserID: { editable: false },
CompanyID: { editable: false },
FirstName: { type: "string", validation: { required: { message: "Name is required"} } },
LastName: { type: "string", validation: { required: { message: "Name is required" } } },
Email: {
type: "string",
validation: {
required: { message: "Email is required." },
validateEmailFormat: function(input) {
if (input.attr("data-bind") == "value:Email") {
input.attr("data-validateEmailFormat-msg", "Email format invalid.");
return checkEmail(input.val());
}
return true;
}
}
},
PhoneNumber: { type: "string" },
Extension: { type: "string" }
}
}
With this code, all fields are being validated when trying to save/update. I don't want Extension or PhoneNumber to validate.
In your update/Save action, You can remove your fields from the ModelState which don't want to valid, like :
ModelState.Remove("PhoneNumber");
ModelState.Remove("Extension");

Kendo ui grid filed with editor, pop up won´t close

I have a field on my kendo ui grid which uses an editor:
columns:[{ field:"Nome", title: "Nome" },{ field: "idTipoQuarto", title:"Tipo de Quarto", editor: tipoQuartoEditor},
In my model i have:
schema:
{
data: "data",
total: function(response)
{
return $(response.data).length;
},
model:
{
id: "idQuarto",
fields:
{
idQuarto: { editable: false, nullable: true },
Nome: { validation: { required: true } },
idTipoQuarto: { validation: { required: true }}
}
}
}
And my editor function is:
function tipoQuartoEditor(container, options)
{
$('<input data-text-field="Nome" data-value-field="Nome" data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
autoBind: false,
dataSource: new kendo.data.DataSource({
transport:
{
read:
{
url: "data/quartos.php",
},
parameterMap: function(options, operation)
{
if (operation !== "read" && options.models)
{
return {models: kendo.stringify(options.models)};
}
}
},
schema:
{
data: "data",
model:
{
id: "idTipoQuarto",
value: "Nome"
}
}
})
});
}
I can see the values when my popup is opened in the drop-down list, and i can post the selections to my database when clicking on the update/insert button, but the popup won´t disappear. It shows me an error that i don´t understand:
Object {xhr: Object, status: "parsererror", errorThrown: SyntaxError: Unexpected token A, sender: ht.extend.init, _defaultPrevented: false…}
What am i missing here, i have seen another post but with no luck adapting to my problem.
Anyone?
Thanks for your time, regards

KendoUI Grid: Non-editable column?

http://jsfiddle.net/bhoff/ZCyPx/50/
$("#grid").kendoGrid({
dataSource:{
data:entries,
schema:{
parse:function (response) {
$.each(response, function (idx, elem) {
if (elem.time && typeof elem.time === "string") {
elem.time = kendo.parseDate(elem.time, "HH:mm:ss");
}
if (elem.datetime && typeof elem.datetime === "string") {
elem.datetime = kendo.parseDate(elem.datetime, "HH:mm:ss");
}
});
return response;
}
}
},
columns:[
{ command: [ "edit" ] },
{ field:"type", title:"Cash Transation Type" },
{ field:"begintime", title:"Begin Time(CT)", format:"{0:hh:mm tt}", editor: timeEditor },
{ field:"endtime", title:"End Time(CT)", format:"{0:hh:mm tt}", editor: timeEditor },
],
editable:"inline",
navigatable:true
});
Based on my example how do I stop the user from editing my "Cash Transation Type" column?
Does it have something to do with this -> editable:"inline" ?
look here
you need to set in the datasource
<script>
var dataSource = new kendo.data.DataSource({
schema: {
model: {
id: "ProductID",
fields: {
ProductID: {
//this field will not be editable (default value is true)
editable: false,
// a defaultValue will not be assigned (default value is false)
nullable: true
},
ProductName: {
//set validation rules
validation: { required: true }
},
UnitPrice: {
//data type of the field {Number|String|Boolean|Date} default is String
type: "number",
// used when new model is created
defaultValue: 42,
validation: { required: true, min: 1 }
}
}
}
}
});
</script>
You would normally set this on your DataSource on the schema.model.fields.
var data = new kendo.data.DataSource({
schema: {
model: {
fields: {
type: { editable: "false" }
Add editable in the field you do not want to enable Edit,
columns:[
{ command: [ "edit" ] },
{ field:"type", title:"Cash Transation Type", editable: false },
{ field:"begintime", title:"Begin Time(CT)", format:"{0:hh:mm tt}", editor: timeEditor },
{ field:"endtime", title:"End Time(CT)", format:"{0:hh:mm tt}", editor: timeEditor },
],
editable:"inline",
navigatable:true
});

kendo ui how to filter dataSource requestStart

Main Problem
My current problem is the refresh progress when updating a grid datasource. I have change my code use the kendo.ui.progress in that way when requestStart event starts I ser the kendo.ui.progress to true. This activates the loading image when it end it calls the requestEnd.
The problem is that this event is hapenning for sorting and filtering. And I want it to only trigger for the read function of the dataSource. This problem makes the grid to use the progress endlessly.
Is there some way to filter in the requestStart and requestEnd only activate on the transport read?
My DataSource Code
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: url_Obtener_Periodo,
type: "POST"
},
parameterMap: function (options, operation) {
if (operation == "read" && options) {
return {
"periodo.Year": $("#periodo-anio").val(),
"periodo.Month": $("#periodo-mes").val(),
"Filtro": $("#Filtro").val()
};
}
}
},
requestStart: function (e) {
kendo.ui.progress($("#grid-container"), true);
},
requestEnd: function (e) {
kendo.ui.progress($("#grid-container"), false);
},
schema:{
model: {
id: "Codigo_De_Pedido",
fields: {
Codigo_De_Pedido: { type: "number" },
Fecha_Y_Hora_De_Creacion: { type: "date" },
UserName: { type: "string" },
Nombre_Del_Usuario: { type: "string" },
Codigo_Del_Vendedor: { type: "number" },
Nombre_Del_Vendedor: { type: "string" },
Is_Pedido_Closed: { type: "bool" },
Estado: { type: "string" }
}
}
},
pageSize: 10
});
The changes I did to solve the progress endlessly problem where 2.
Removing requestEnd function from the dataSource
Adding dataBound function to the Grid
Data Source Code
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: url_Obtener_Periodo,
type: "POST"
},
parameterMap: function (options, operation) {
if (operation == "read" && options) {
return {
"periodo.Year": $("#periodo-anio").val(),
"periodo.Month": $("#periodo-mes").val(),
"Filtro": $("#Filtro").val()
};
}
}
},
schema:{
model: {
id: "Codigo_De_Pedido",
fields: {
Codigo_De_Pedido: { type: "number" },
Fecha_Y_Hora_De_Creacion: { type: "date" },
UserName: { type: "string" },
Nombre_Del_Usuario: { type: "string" },
Codigo_Del_Vendedor: { type: "number" },
Nombre_Del_Vendedor: { type: "string" },
Is_Pedido_Closed: { type: "bool" },
Estado: { type: "string" }
}
}
},
pageSize: 10,
requestStart: function (e) {
kendo.ui.progress($("#grid-container"), true);
}
});
Kendo Grid Code
kendoGrid = $("#selectable-pedidos").kendoGrid({
dataSource: dataSource,
pageable: true,
sortable: true,
filterable: {
extra: false,
operators: {
string: {
startswith: "Comienza Con",
eq: "Es Igual A",
neq: "No Es Igual A"
}
}
},
dataBound: function (e) {
kendo.ui.progress($("#grid-container"), false);
},
columns: [
{ field: "Fecha_Y_Hora_De_Creacion", title: "Fecha y Hora", template: "#= kendo.toString(Fecha_Y_Hora_De_Creacion, 'dd/MM/yyyy hh:mm:ss tt') #" },
{ field: "Codigo_De_Pedido", title: "Código de Pedido" },
{ field: "Estado", filterable: true, title: "Estado" },
{ field: "Codigo_Del_Vendedor", title: "Código de Vendedor" },
{ field: "Nombre_Del_Vendedor", title: "Nombre de Vendedor" },
{
command: {
text: "Ver Detalle de Pedido",
click: function (e) {
$("#empty").append("<form method='POST' action='/HojaDeRuta/GetById/'><input type='hidden' name='Codigo_Pedido' value='"
+ this.dataItem($(e.currentTarget).closest("tr")).Codigo_De_Pedido + "' /><input type='submit' /></form>");
$("#empty input[type='submit']").click();
}
},
title: " "
}
]
}).data("kendoGrid");
There are a few things about your questions worth mentioning for those who read this:
Is there some way to filter in the requestStart and requestEnd only
activate on the transport read?
Yes, but it will not help you. The parameter of the event has a type property that will contain read, update, destroy or create.
statementEntriesDS.bind("requestStart", function (e) {
switch (e.type) {
case "create":
alert('-> event, type "create".');
break;
case "read":
alert('-> event, type "read".');
break;
case "update":
alert('-> event, type "update".');
break;
case "destroy":
alert('-> event, type "destroy".');
break;
}
});
Your example code doesn't specify serverFiltering or serverSorting so sorting and filtering wouldn't cause an remote action. You'll only get client-side sorting and filtering. However, if they are specified they're all going to result in a read and that wouldn't really help you.
That you would not have the requestEnd event fire sounds odd. You should probably add a handler for the error event and see if something is failing.
If you really want complete control over what's happening, you can specify a function for your read:
transport: {
read: function (options) {
kendo.ui.progress($gridContainer, true);
$.ajax({
url: carrierServiceBaseUrl + "/GetManualStatementsCarrierList",
contentType: 'application/json; charset=utf-8',
dataType: "json",
type: "POST",
success: function (result) {
// notify the data source that the request succeeded
options.success(result);
kendo.ui.progress($gridContainer, false); },
error: function (result) {
options.error(result); // Call the DataSource's "error" method with the results
kendo.ui.progress($gridContainer, false);
notification.show({
title: "ERROR:",
message: result.statusText
}, "error");
}
});
}
}

Resources