How to validate kendo DateTimePickerFor using mvc 4 razor? - javascript

i wants to validate kendo DateTimePickerFor on client side.My control on view as
#(Html.Kendo().DateTimePickerFor(m => m.StartDate)
.HtmlAttributes(new { style = "width:200px", #class = datePicker",required = "true" })
.Name("StartDate")
.Depth(CalendarView.Year)
.Value(DateTime.Now.ToString())
.Min(DateTime.Now.ToString())
.Max(DateTime.Now.AddMonths(4))
.Format("MM/dd/yyyy hh:mm tt")
)
i have masked it in ready function.but it allows me to type any input.
$(document).ready(function () {
$('.datePicker').mask('99/99/9999');
$('#_appointmentCreateForm input[type="text"], textarea').tooltipster({
trigger: 'custom',
onlyOne: false,
position: 'right',
appendTo: "#_appointmentCreateForm"
});
$('#_appointmentCreateForm').validate({
ignore: [],
rules: {
StartDate: {
required: true
}
},
messages: {
StartDate: {
required: "Please choose Date and Time."
}
},
errorPlacement: ValidatorErrorPlacement,
success: ValidatorSuccess
}
);
});
And when there is no value in datetimepicker i.e datetimepicker is empty then validation gets fail but not showing any message.
So, any ideas how I can validate the Kendo DateTimePicker to accept valid input format? Thanks in advance.

You can define
Html.Kendo().DateTimePickerFor(model => model.date_debut)
.ParseFormats(new string[] { "dd/MM/yyyy HH:mm" })
on the control. But this will be a server side validate as Html.Kendo() will generate the control from the model.
To validate it in client side, the best way is to test when the submit is fired.
$.submit(function(e) {
//test if form is ok
});

My problem has been solved!when i changed my ready function to
$(document).ready(function () {
$('.datePicker').mask('99/99/9999');
$('#_appointmentCreateForm input[type="text"], textarea').tooltipster({
trigger: 'custom',
onlyOne: false,
position: 'right',
appendTo: "#_appointmentCreateForm"
});
$('#_appointmentCreateForm').validate({
ignore: [],
rules: {
Speciality: {
selectspeciality: true
}
},
messages: {
Speciality: {
selectspeciality: "Please select Speciality."
}
},
errorPlacement: ValidatorErrorPlacement,
success: ValidatorSuccess
}
);
$.validator.addMethod("selectspeciality", function (value, element) {
var isValid = $(element).data("kendoDropDownList").selectedIndex == 0 ? false : true;
return this.optional(element) || isValid;
}, "Please select Speciality.");
});
Ho[e it will help someone like me.

Related

validating that a canvas has been drawn in

I'm implementing an online waiver where a client has to sign into canvas before they can complete the form. I use Signature_Pad from szimek and jquery-validate and would like to have the canvas (which is part of the form) be included. I tried a custom formatter, like so:
let wrapper = document.getElementById("signature_pad");
var signaturePad = new SignaturePad(wrapper.querySelector("canvas"), {
backgroundColor: 'white'
});
jQuery.validator.addMethod("checkSignature", function(value, element) {
return signaturePad.isEmpty() == false;
}, "Signature must be provided");
$("form[name='form-waiver']").validate({
rules: {
WaiverName: {
required: true,
minlength: 2
},
signature_pad: {
checkSignature: true
}
},
messages: {
WaiverName: "The name has to be filled out"
},
successClass: "valid",
errorClass: "invalid",
submitHandler: function (form) {
...
}
};
However, the form validates even if the canvas is empty. Is there a method to include the canvas in the form validation?

How change JQuery Validation Message without refreshing website [duplicate]

This question already has answers here:
jquery .validate() variable error message
(3 answers)
Closed 1 year ago.
I am using jQuery Validation from here: https://jqueryvalidation.org. Currently, I have two types of Messages prepared. They are popping out. When I'm changing language on web variables global variable with messages also is changing, but message in validator don't. Language of the validator change after I refresh the website. How can I change it on live without refreshing the website?
HTML is no needed, because everything is happening in JS file.
This is a function that are changing values in the object.
JS:
function setLang(lang) {
(lang) ? lang: "pol";
if (lang == "pol") {
Messages = {
formFirstnameRequired: 'Pole imie jest wymagane!',
formLastnameRequired: 'Pole nazwisko jest wymangane!',
formEmailRequired: 'Pole email jest wymagane!',
formTitleRequired: 'Pole Tytuł jest wymagane!',
formMessageRequired: 'Pole wiadomość jest wymagane!',
}
} else if (lang == "eng") {
Messages = {
formFirstnameRequired: 'Field firstname is required!',
formLastnameRequired: 'Field lastname is required!',
formEmailRequired: 'Field email is required!',
formTitleRequired: 'Field title is required!',
formMessageRequired: 'Field message is required!',
}
}
}
I'm also using this cookie for managing the language of this form validation:
if (getCookie("lang") == null) {
document.cookie = 'lang=pol';
}
setLang(getCookie("lang"));
$(".nav").on("click", "#polLang", (event) => {
document.cookie = 'lang=pol';
setLang(getCookie("lang"));
});
$(".nav").on("click", "#engLang", (event) => {
document.cookie = 'lang=eng';
setLang(getCookie("lang"));
});
Here I have validation
JS:
$("#contactForm").validate({
rules: {
"formFirstname": {
required: true,
},
"formLastname": {
required: true,
},
"formEmail": {
required: true,
},
"formTitle": {
required: true,
},
"formMessage": {
required: true,
}
},
messages: {
"formFirstname": {
required: Messages.formFirstnameRequired,
string: true
},
"formLastname": {
required: Messages.formLastnameRequired,
string: true
},
"formEmail": {
required: Messages.formEmailRequired,
email: true,
},
"formTitle": {
required: Messages.formTitleRequired,
string: true
},
"formMessage": {
required: Messages.formMessageRequired,
string: true
}
},
onfocusout: false,
errorPlacement: function(error) {
toastr.error(error);
},
submitHandler: function(form) {
toastr.success('success')
return false;
},
invalidHandler: function() {
return;
}
});
Jquery validator msgs are static. If you want to update them dynamically you can create a function, that will return a new msg.
Like this:
"formFirstname": {
required: function getFormFirstname() { return Messages.formFirstnameRequired },
string: true
},

How do I trigger a jQuery code while using the jQuery validation library?

I am using jQuery validation library to validate both password inputs to have the same value. My code is written below.
$(".woocommerce-ResetPassword").validate({
onfocusout: false,
onkeyup: false,
rules: {
password_2: {
equalTo: "#password_1"
}
},
messages: {
password_2: "<div class='woocommerce-password-strength bad'>Passwords do not match</div>"
},
submitHandler: function(form) {
return true;
}
});
I want to execute a jQuery code to add a class to an element when the notification of password_2 appears.
I want to modify this part of the code by adding a jQuery script inside the messages: {} but the code below does not work. You can see that I added $(".woocommerce-form-row--last").addClass("notif-triggered");
messages: {
password_2: "<div class='woocommerce-password-strength bad'>Passwords do not match</div>"
$(".woocommerce-form-row--last").addClass("notif-triggered");
},
Any help is greatly appreciated. Thanks.
You don't tell us, but I'll assume you're using the validation library linked here.
You should be able to add functionality within an invalidHandler, e.g. something think this:
$(".woocommerce-ResetPassword").validate({
onfocusout: false,
onkeyup: false,
rules: {
password_2: {
equalTo: "#password_1"
}
},
messages: {
password_2: "<div class='woocommerce-password-strength bad'>Passwords do not match</div>"
},
submitHandler: function(form) {
$(".woocommerce-form-row--last").removeClass("notif-triggered");
return true;
},
invalidHandler: function(event, validator) {
$(".woocommerce-form-row--last").addClass("notif-triggered");
}
});

Drop down and datepicker triggers on jquery validation

I am using codeigniter where I have autocomplete drop down and datepicker. If values are not selected then I am applying validations using jquery. Validations run properly but when I click on submit button drop down list or date picker gets auto trigger if not selected. I dont understand why this is happening
Date Picker is
$(function ()
{
$('#search_date').datepicker
({
format: "dd-mm-yyyy",
autoclose: true,
clearBtn : "true" ,
startDate: new Date() ,
})
});
validations are
$( document ).ready(function() {
$(":submit").on('click',function(){
$('#search_form').validate({
rules: {
loading:
{
required:true
},
discharge:
{
required:true
},
search_date:
{
required:true
}
},
messages: {
loading:
{
required:"Required!"
},
discharge:
{
required:"Required!"
},
search_date:
{
required:"Required!"
}
errorElement: "span",
errorPlacement: function(error, element) {
error.appendTo(element.parent());
},
submitHandler: function (form) {
if ($(form).valid())
form.submit();
return false; // prevent normal form posting
}
});
});
});

Jquery custom validation with Html 5 data attributes and default value

I am trying to build a custom client side jquery validation and trying to ignore default values that i generate from HTML5 data attributes
$('input, textarea').each(function () {
if ($(this).data('val-default')) {
$(this).focus(function () {
if (this.value == $(this).data('val-default'))
this.value = '';
});
$(this).blur(function () {
if (this.value == '')
this.value = $(this).data('val-default');
});
this.value = $(this).data('val-default');
}
});
So with the above code i can add default values to input and textarea elements like this
data-val-default="Type your first name here"
Placeholder attribute is unfortunately not an option yet
The problem now is that i am trying to validate these elements with Jquery validation like this
$.validator.addMethod("ignoreDefaultValues",
function (value, element) {
if ($(element).data('val-default'))
return !($(element).data('val-default') == element.value);
return true;
},
"Required field"
);
$('form#contact-form').submit(function (e) {
e.preventDefault();
if (!$(this).valid({
rules:
{
title:
{
ignoreDefaultValues: true,
required: true
},
description:
{
ignoreDefaultValues: true,
required: true
},
name:
{
ignoreDefaultValues: true,
required: true
},
email:
{
ignoreDefaultValues: true,
required: true
}
}
})) {
alert("NOT VALID!");
}
else
{
alert("IS VALID!");
//todo: ajax post to server
}
});
Here is an example of an input element
<input type="text" class="firstname" name="firstname" data-val-default="Type your first name here" data-val="true" data-val-required="*" />
The jquery validation seems to ignore the rules. if i test for example by typing an empty space it will validate and alert "NOT VALID" but it just ignores my custom validation.
What am i doing wrong?
Have i missed anything?
You need to setup the validation before the submit function. So instead of doing $(this).valid(...) in your submit handler, instead do this beforehand:
$('form#contact-form').validate( { //your rules
,
submitHandler:function(){
alert('Is Valid!');
$(this).submit(); //or submit via AJAX, or whatever you planned...
},
invalidHandler:function(){
alert('Is not valid!');
}
});

Categories

Resources