Jquery custom validation with Html 5 data attributes and default value - javascript

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!');
}
});

Related

Jquery validation, alert just once

If I run below, and both fields alder and gender is invalid, it'll alert two times. Is it possible to make it alert just once?
$(function(){
$("#formTest").validate({
rules : {
alder : {
required: true
},
gender : {
required: true
}
},
errorPlacement: function (error, element) {
alert("Alert once");
}
});
});
errorPlacement is called once for every error - it's not meant to alert a message, but to place it in the form. You can either try to use the groups feature, to group you fields together and get a single call for the entire group, or use the showErrors function to capture all errors and present them however you like:
$(".selector").validate({
showErrors: function(errorMap, errorList) {
alert(`Your form contains ${this.numberOfInvalids()} errors`);
}
});
Never used jQuery validate before but this might work:
$(function(){
var checked = false;
$("#formTest").validate({
rules : {
alder : {
required: true
},
gender : {
required: true
}
},
errorPlacement: function (error, element) {
if (!checked) {
alert("Alert once");
checked = true;
}
}
});
});

How to dynamically add a validation rule using jquery validation plugin

I'm trying to dynamically add a validation rule to some dynamic controls using http://jqueryvalidation.org/ but its not working.
$(".rtxt").each(function () {
$(this).rules('add', {
required: true
});
});
<input class='rtxt' name='txtDocName' id='txtDocName' style='width:220px;' type='text' >
Don't know what i am missing here.
I can't use 'required' attribute as its not supported by IE9 so i will have to use jquery validation plugin.
Here is fiddle
http://jsfiddle.net/ed4fg1xo/
Also, i need to do validation on div click event.
$(document).ready(function () {
// 1. prepare the validation rules and messages.
var rules = {
textbox1: {
required: true,
minlength: 2
},
textbox2: "required",
textbox3: "required"
};
var messages = {
textbox1: {
required: "textbox1 is required",
minlength: "textbox1 needs to be at least length 2"
},
textbox2: "textbox2 is requried",
textbox3: "textbox3 is required"
};
// 2. Initiate the validator
var validator
= new jQueryValidatorWrapper("FormToValidate",
rules, messages);
// 3. Set the click event to do the validation
$("#DivIdName").click(function () {
if (!validator.validate())
return;
alert("Validation Success!");
});
});

Using jQuery Validation Plugin with dynamic form elements

I have a page that contains multiple forms, and each form can contain any number of elements that have a common root in its name. I'm trying to use this answer to validate a form when it's submitted, but I get a TypeError: a.data(...) is undefined error on jquery.validate.js. My code is below.
var valForm = function(kit_id) {
$('input[name^="kit_desc_"]').each(function() {
$(this).rules("add", {
required: true,
messages: {
required: "Please enter a description"
}
});
});
$("#frm_" + kit_id).validate({
errorElement: "div",
errorPlacement: function(error, element) {
$("#error_modal").html(error);
}
});
if (! $("#frm_" + kit_id).valid()) {
// a dialog box will appear listing the errors.
$("#error_modal").dialog();
}
};
The function is called when a link is clicked.
Save
Any suggestions?
I think you have to call .validate() on the form before you can call .rules() on the inputs in that form. You should also call .rules() only on the inputs in the form you're submitting.
var valForm = function(kit_id) {
var form = $("#frm_" + kit_id);
form.validate({
errorElement: "div",
errorPlacement: function(error, element) {
$("#error_modal").html(error);
}
});
form.find('input[name^="kit_desc_"]').each(function() {
$(this).rules("add", {
required: true,
messages: {
required: "Please enter a description"
}
});
});
if (! form.valid()) {
// a dialog box will appear listing the errors.
$("#error_modal").dialog();
}
};

Simplifying Form validation

I have a form with 5 input fields (4 text input, 1 checkbox) and I have written this code to handle missing information in the input fields. The code works fine but but it seems repetitive and inefficient. Is there a simpler way to write this code?
$("#main-form").on('submit', function(event) {
if (!$("#field1").val()) {
event.preventDefault();
$("#field1-error").html("Error!");
}
else
$("#field1-error").html("");
if (!$("#field2").val()) {
event.preventDefault();
$("#field2-error").html("Error");
}
else
$("#field2-error").html("");
if (!$("#field3").val()) {
event.preventDefault();
$("#field3-error").html("Error");
}
else
$("#field3").html("");
if (!$("#field4").val() && !$("#checkbox1").prop('checked')) {
event.preventDefault();
$("#field4-error").html("Error");
}
else
$("#field4-error").html("");
});
If the function does the same thing on multiple similar fields, it is best to just write one function. I think every Javascript engineer at some point or another has banged their head against a wall trying to come up with a slicker way run form validations.
For this situation I would write the function and call it whenever I needed it. Try this:
$("#main-form").on('submit', function(event) {
myValidations.contentsPresent('#field1', '#field1-error');//call the first field validaitions
myValidations.contentsPresent('#field2', '#field2-error');//second
//third
//etc
});
var myValidations =
{
contentsPresent: function(fieldId, errorId)
{
if (!$(fieldId).val()) {
event.preventDefault();
$(errorId).html("Error!");
}
else
$(errorId).html("");
}
},
contentsPresentCheckBox: function(fieledId, checkboxId, errorId)
{
if (!$(fieledId).val() && !$(checkboxId).prop('checked')) {
event.preventDefault();
$(errorId).html("Error");
}
else
$(errorId).html("");
}
}
}
//Try this.
$(document).ready(function(){
/** Form Validation */
$("#formId").validate({
rules: {
field1:{ required: true },
field2:{ required: true },
field3:{ required: true },
field4:{ required: true }
},
messages: {
field1:{ required: 'Field1 is required!' },
field2:{ required: 'Field2 is required!' },
field3:{ required: 'Field3 is required!' },
field4:{ required: 'Field4 is required!' }
}
// Submit function
});
// This is a simple jquery form validation but you need to include the jquery validation plugin.
http://jqueryvalidation.org/

How to validate kendo DateTimePickerFor using mvc 4 razor?

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.

Categories

Resources