Showing posts with label jQuery Validation. Show all posts
Showing posts with label jQuery Validation. Show all posts

Monday, August 25, 2014

How to easily validate form and inputs using jQuery

Validation is an important and required functionality for any application. Without proper validations of input, you application will die. So here is a jQuery plugin named "Valideasy " which helps you to validate your forms and input control without worrying about writing long lines of code.
Valideasy is a jQuery plugin that you can use in form validation without writing complex JS script. Everything's done via HTML attributes added to your form fields. And it is is compatible with all modern browsers, starting from IE7. This plugins also allows you to easily customize the validation error message.

You may also like:
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Monday, June 16, 2014

How to validate all countries phone numbers using jQuery

Earlier I had posted about "Validate phone numbers using jQuery" but that code just validates for valid input, it doesn't check for format of phone number. But recently a jQuery plugin named "International Telephone Input"is released which validates all the international phone numbers along with country code.

International Telephone Input jQuery plugin for entering international telephone numbers. It adds a flag dropdown to any input, which lists all the countries and their international dial codes next to their flags.


You may also like:

Features


  • In the country dropdown you can navigate by typing, or using the up/down keys
  • Selecting a country from the dropdown will update the dial code in the input
  • Typing a different dial code automatically updates the displayed flag
  • Country names in the dropdown also include localised versions in brackets
  • Lots of initialisation options for customisation, as well as public methods for interaction

How to use it?


To use this plugin, all you need to do is to download the latest version and then link the required stylesheet and reference to plugin library.
<link rel="stylesheet" href="build/css/intlTelInput.css">
Add the plugin script and initialise it on your input element
<input type="tel" id="mobile-number">

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="build/js/intlTelInput.min.js"></script>
<script>
  $("#mobile-number").intlTelInput();
</script>

Examples


  • Validation:
    Use Google's libphonenumber for validation
  • Lookup user's country:
    Use IP address lookup to set the default country to the user's country
  • Country sync:
    Access the country data to create a separate country dropdown for an address form, and then listen for change events to keep the two dropdowns in sync
  • European countries:
    Only show European country codes
  • Styling:
    Displays the two different styling settings
  • Modify country data:
    Modify the data to only show localised country names

This jQuery plugins also provides options for customization like for setting default country, dial code delimiter and many more. You can visit the official website for more information.

Official Website
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Friday, May 30, 2014

15+ Useful jQuery Validation Plugins

Collection of 15+ Useful jQuery Form Validation Plugins.

Form validation is required for better user experience and for security purpose. But implementation of validation can give you serious headache. To save you from serious head bashing, here is a list of 15+ jQuery Form Validation Plugins, that will make form validation easy.

You may also like:

jQuery Validation Plugin


jQuery Validation Plugin makes simple clientside form validation trivial, while offering lots of option for customization.

The plugin comes bundled with a useful set of validation methods, including URL and email validation, while providing an API to write your own methods. All bundled methods come with default error messages in english and translations into 36 locales.


Validetta


Validetta is a tiny jQuery plugin which you can do client-side validation of your forms. It aims to decrease your burden with easy usage and flexible structure. It is currently supported in current stable releases of Chrome, Firefox, Opera, Safari as well as IE8 and up. This plugins works with every input control like text, list, radio button, checkboxes etc..


Formance.js


Formance.js is a jQuery library for formatting and validating form fields. It supports form fields like Credit card, Date, EMail, Phone number etc..


jQuery.validationEngine


jQuery validation engine is a Javascript plugin aimed at the validation of form fields in the browser (IE 6-8, Chrome, Firefox, Safari, Opera 10). The plugin provides visually appealing prompts that grab user attention on the subject matter.
Validations range from email, phone, and URL, to more complex calls such as ajax processing or custom javascript functions. Bundled with many locales, the error prompts can be translated into the language of your choice.


nextVal


nextVal is an easy-to-use, flexible and robust form validation plugin for jQuery. Each input should have a validate attribute. Elements can also have placeholder and title attributes. Also validate attribute can be passed multiple values.


bValidator


bValidator is a jQuery plug-in for client side form validation. It supports fully customized error messages defined with template and CSS, many validation functions (actions) like date, email, URL, IP address, validation of dynamic forms, customized validation functions and more.


Ajax Fancy Captcha


Ajax Fancy Captcha is a jQuery plugin that helps you protect your web pages from bots and spammers. We are introducing you to a new, intuitive way of completing “verify humanity” tasks. In order to do that you are asked to drag and drop specified item into a circle.


jQuery Credit Card Validator


jQuery Credit Card Validator detects and validates credit card numbers. It’ll tell you the detected credit card type and whether the number length and Luhn checksum are valid for the type of card.


Goodness


Goodness is a light jQuery form validation plugin. There are no included validation rules*, feedback markup or error styles. Instead, you make the rules and use the names as classes in your own markup. When the form is validated, classes will be added or removed from your markup to match your defined styles and animation.


Validity


jQuery.validity is a plugin designed to aid in the configuration of clientside form-validation. Validity was concieved with three goals which are Easy setup, Unobtrusive JavaScript and Customizable Appearence. In style, validity makes use of jQuery's selector engine and follows its pattern of method chaining.


Motion Captcha


MotionCAPTCHA is a jQuery CAPTCHA plugin, based on the HTML5 Canvas, requiring users to sketch the shape they see in the canvas in order to submit a form. At the moment, it’s just a proof-of-concept – it only uses client-side gesture recognition, and doesn’t really have IE support.


Creditly.js


Creditly.js is a jQuery plugin for creating an input masked form with input validation for your customers that makes it easier to input credit card information.


Formly


Formly is a jQuery Plugin for easily adding cross-browser styling and validation to forms. Formly makes adding forms to your site a bit more exciting. Easily add style, validation, and a more impressive user interaction with a single function.


NumBox


The NumBox jQuery Plugin helps ensure that a numeric keyboard will pop-up on mobile devices when a number is entered. It offers real-time validation as you type plus display formatting for mobile devices and desktop browsers, is designed for HTML5's input type="number" elements, and provides a number of customization options.


Pliant


Pliant is a jQuery validation plugin that allows easy extending/overriding of rules, as well as defining field validation by html comments.


Happy Js


Lightweight form validation for jQuery or Zepto.js


Strength.js


The ultimate jQuery password input plugin. Featuring secure strength indicator and hide/show password.


Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Wednesday, April 10, 2013

Restrict Date Range in jQuery UI DatePicker for two dates

In this post, you will learn how to implement validation to "Restrict Date Range in jQuery UI DatePicker" or "End Date should be greater than Start Date by few days using jQuery Date Picker". When I say few days, which means end date must be at least StartDate + 4 or StartDate + 2.. The number can be anything depending on your requirement.

Related Post:

Following things needs to be taken care.
  1. When Start Date is selected, then need to disable all the dates before selected start date + 4 days in end date datepicker. "minDate" option is our choice here.
  2. If end date is selected first, then disable all the dates after selected end date - 4 days in Start date datepicker. "maxDate" option is our choice here.
To implement this, write code in jQuery UI Datepicker "onSelect" event which gets called when date is selected.
$(document).ready(function () {
   var daysToAdd = 4;
   $("#txtFromDate").datepicker({
      onSelect: function (selected) {
         var dtMax = new Date(selectedDate);
         dtMax.setDate(dtMax.getDate() + daysToAdd); 
         var dd = dtMax.getDate();
         var mm = dtMax.getMonth() + 1;
         var y = dtMax.getFullYear();
         var dtFormatted = mm + '/'+ dd + '/'+ y;
         $("#txtToDate").datepicker("option", "minDate", dtFormatted);
      }
   });

   $("#txtToDate").datepicker({
      onSelect: function (selected) {
         var dtMax = new Date(selected);
         dtMax.setDate(dtMax.getDate() - daysToAdd); 
         var dd = dtMax.getDate();
         var mm = dtMax.getMonth() + 1;
         var y = dtMax.getFullYear();
         var dtFormatted= mm + '/'+ dd + '/'+ y;
         $("#txtFromDate").datepicker("option", "maxDate", dtFormatted)
      }
   });
});
The above jQuery code,
  • First, takes the selected date and converts it in Date Object.
  • And then adds/subtracts "daysToAdd" variable.
  • And it sets formatted date to Datepciker.
If you also want to make sure that Start Date should be greater than end Date then set "minDate : 0" for from date datepicker.
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Wednesday, March 13, 2013

jQuery Validation With ASP.NET Web Forms

Find out jQuery code to perform validation for ASP.NET Web forms. The code includes validations for email address, phone number, date, date format, ASP.NET Drop Down, ASP.NET Textbox, ASP.NET Textbox with only number and many more validation techniques.


Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Monday, January 28, 2013

All kind of Client Side Validation using jQuery

Validation is most important and required feature on any web page. And Client side validation plays an important part. So find jQuery code to validate email address, phone number, date, date format, textbox with only number and many more validation techniques.


Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, December 18, 2012

jQuery code to check if all textboxes are empty

Find jQuery code to check if all the input type 'text' element or textboxes are empty or not. This is quite useful for validation. This jQuery code loops through all the textboxes and check their value. If value is empty then it adds a red color border to let user know that this field is required.
$(document).ready(function() {
    $('#btnSubmit').click(function(e) {
        var isValid = true;
        $('input[type="text"]').each(function() {
            if ($.trim($(this).val()) == '') {
                isValid = false;
                $(this).css({
                    "border": "1px solid red",
                    "background": "#FFCECE"
                });
            }
            else {
                $(this).css({
                    "border": "",
                    "background": ""
                });
            }
        });
        if (isValid == false) 
            e.preventDefault();
        else 
            alert('Thank you for submitting');
    });
});​
See result below


See Complete Code
As you can see that in above demo, all the textboxes are validated but what if when you want to validate only some of them, not all. For example, from above demo you only want to validate all the fields excluding "Age".

So to achieve this, assign a css class to all textboxes which needs to be validated and change selectors to select only those textbox which have that class.
$('input[type="text"].required').each(function() {
});

See Complete Code
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Monday, July 9, 2012

Validate ASP.NET DropDownList using jQuery

In this small post, today I will show you how to validate ASP.NET DropDown List using jQuery.

Let's declare a DropDownList.
<asp:DropDownList ID="ddlList" runat="server">
   <asp:ListItem Text="Select" Value="0" />
   <asp:ListItem Text="jQuery" Value="1"></asp:ListItem>
   <asp:ListItem Text="JavaScript" Value="2"></asp:ListItem>
   <asp:ListItem Text="Prototype" Value="3"></asp:ListItem>
   <asp:ListItem Text="Dojo" Value="4"></asp:ListItem>
   <asp:ListItem Text="Mootools" Value="5"></asp:ListItem>
</asp:DropDownList>
To validate the dropdown list, all you need to do is to get the selected value and check if it is not 0. If 0, then nothing is selected so alert the user, otherwise proceed.
$(document).ready(function() {
    $('#btnValidateByVal').on('click', function(e) {
        var iVal = $('#ddlList').val();
        if (iVal == 0) 
        {
            alert('Please select any technology.');
            e.preventDefault();
        }
        else 
            alert('Well Done!!!!');
   })
})​
In the above jQuery code, the validation is done using value of the selected item. But you can also validate the dropdown using the selected item text.
$(document).ready(function() {
    $('#btnValidateByText').on('click', function(e) {
        var sText = $('#ddlList1 option:selected').text().toLowerCase();
        if (sText == 'select') 
        {
            alert('Please select any technology.');
            e.preventDefault();
        }
        else 
           alert('Well Done!!!!');
    })
})​
Note: Above both jQuery codes will work only with jQuery 1.7 or higher version as I have used .on() method to bind the click event and .on was introduced in jQuery 1.7. So if you are using below version then you can either .live() or .bind() method.

Suggested Post,
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Wednesday, July 4, 2012

Validate ASP.NET RadioButtonList using jQuery

ASP.NET RadioButtonList control is used to create a group of radio buttons, where all are rendered as an individual <input type=radio></input>. So in this post, I will show you how to validate ASP.NET RadioButtonList using jQuery.

Let's declare a RadioButtonList.
<asp:RadioButtonList ID="rdlList" runat="server">
    <asp:ListItem Text="jQuery" Value="jQuery"></asp:ListItem>
    <asp:ListItem Text="JavaScript" Value="JavaScript"></asp:ListItem>
    <asp:ListItem Text="Prototype" Value="Prototype"></asp:ListItem>
    <asp:ListItem Text="Dojo" Value="Dojo"></asp:ListItem>
    <asp:ListItem Text="Mootools" Value="Mootools"></asp:ListItem>
</asp:RadioButtonList>
As you can see there are 5 radio buttons and the validation would be to select at least one option. For demo, I will validate the radiobuttonlist on click of button. We can use length property to find out, if any radio button is selected or not.

$("#rdlList :radio:checked").length; will return 1 if anything is selected, otherwise 0.
$(document).ready(function() {
    $('#btnSubmit').on('click', function(e) {
        var cnt = $("#rdlList :radio:checked").length;
        if (cnt == 0) 
        {
            alert('Select any option.');
            e.preventDefault();
        }
        else 
            alert('Well Done!!!!');
    });
});​
Note: This code will work only with jQuery 1.7 or higher version as I have used .on() method to bind the click event and .on was introduced in jQuery 1.7. So if you are using below version then you can either .live() or .bind() method.

Suggested Post,
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, July 3, 2012

Validate HTML CheckboxList using jQuery

In yesterday's post, I had posted about how to "Validate ASP.NET CheckboxList using jQuery", but pure HTML checkbox list is slightly different. The main problem is that it can't be accessed using ID because every checkbox will have different ID. But they share one common attribute which is "name". So while accessing checkboxes in jQuery, need to use "name" attribute.

Let's declare a HTML checkboxlist.
<input type="checkbox" name="technologies" value="jQuery" /> jQuery <br/>
<input type="checkbox" name="technologies" value="JavaScript" />JavaScript <br/>
<input type="checkbox" name="technologies" value="Prototype" /> Prototype<br/>
<input type="checkbox" name="technologies" value="Dojo" /> Dojo<br/>
<input type="checkbox" name="technologies" value="Mootools" /> Mootools <br/>
As you can see there are 5 checkboxes and the validation would be to select at least 3 technologies. And on click of button, validate the checkboxlist. To find out, how many checkboxes are checked, use length property to find out.

$("input[name='technologies']:checked").length; will give count of checked checkboxes out of the list.
$(document).ready(function() {
    $('#btnSubmit').on('click', function(e) {
        var cnt = $("input[name='technologies']:checked").length;
        if (cnt < 3) 
        {
            alert('Select at least 3 technologies');
            e.preventDefault();
        }
        else 
            alert('Well Done!!!!');
    });
});​
See result below.


See Complete Code
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Monday, July 2, 2012

Validate ASP.NET CheckboxList using jQuery

ASP.NET CheckBoxList is group of checkboxes which is used to create a multi-selection check box group. In this post, I will show you how to validate ASP.NET CheckBoxList using jQuery.

Let's declare a CheckboxList.
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
    <asp:ListItem Text="Singing" Value="Singing"></asp:ListItem>
    <asp:ListItem Text="Writing" Value="Writing"></asp:ListItem>
    <asp:ListItem Text="Travelling" Value="Travelling"></asp:ListItem>
    <asp:ListItem Text="Blogging" Value="Blogging"></asp:ListItem>
    <asp:ListItem Text="Sports" Value="Sports"></asp:ListItem>
</asp:CheckBoxList>
As you can see there are 5 checkboxes and the validation would be to select at least 3 technologies. And on click of button, validate the checkboxlist. To find out, how many checkboxes are checked, use length property to find out.

$("#CheckBoxList1 input:checked").length; will give count of checked checkboxes out of the list.
$(document).ready(function() {
    $('#btnSubmit').on('click', function(e) {
        var cnt = $("#CheckBoxList1 input:checked").length;
        if (cnt < 3) 
        {
            alert('Select at least 3 technologies');
            e.preventDefault();
        }
        else 
            alert('Well Done!!!!');
    });
});​
Note: This code will work only with jQuery 1.7 or higher version as I have used .on() method to bind the click event and .on was introduced in jQuery 1.7. So if you are using below version then you can either .live() or .bind() method.

Suggested Post,
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, May 15, 2012

Validate phone numbers using jQuery

Now days registration forms have phone numbers as mandatory field. But how to validate the entered phone number is correct or not? In this post, I will show you how to validate the phone number using jQuery. To validate the phone number, I have created a function which based on input, returns true or false. It checks for the validity of phone number using regular expression.
//Code Starts
function validatePhone(txtPhone) {
    var a = document.getElementById(txtPhone).value;
    var filter = /^[0-9-+]+$/;
    if (filter.test(a)) {
        return true;
    }
    else {
        return false;
    }
}​
//Code Ends
The above regular expression allows only numerals and + or – signs. Based on your requirement you can modify this regular expression.

Now call this function to validate the phone number. For demo, I have used on blur event of textbox But It can be used on click on button or any another event. Based on the result, it updates the status in a span tag.
//Code Starts
$('#txtPhone').blur(function(e) {
   if (validatePhone('txtPhone')) {
       $('#spnPhoneStatus').html('Valid');
       $('#spnPhoneStatus').css('color', 'green');
   }
   else {
      $('#spnPhoneStatus').html('Invalid');
      $('#spnPhoneStatus').css('color', 'red');
   }
});
//Code Ends
See result below.



Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Wednesday, April 25, 2012

Alert user while typing invalid domain name using jQuery

It is very much possible that at the time of signup, user make mistake while entering the correct domain. For example, instead of "hotmail.com", user types "hotnail.com". And the wrong email address gets saved in database. And later on, when your website sends an email, the email will bounce. In this post, I will show you a jQuery plugin called "Mailcheck" which suggest possible correct domain.

Mailcheck.js is a jQuery plugin that suggests a possible right domain when your users misspell it in an email address. For example when your user types in "[email protected]", Mailcheck will suggest "[email protected]".


How to use it?


All one need to do is to call "mailcheck" function on blur event of the textbox and it will do the rest. Mailcheck takes in two callbacks, suggested and empty.

suggested is called when there's a suggestion. Mailcheck passes in the target element and the suggestion. The suggestion is an object with the following members:
//Code Starts
{
  address: 'test',          // the address; part before the @ sign
  domain: 'hotmail.com',    // the suggested domain
  full: '[email protected]'  // the full suggested email
}
//Code Ends
empty is called when there's no suggestion. Mailcheck just passes in the target element. You can use the callbacks to display the appropriate visual feedback to the user.
//Code Starts
$(document).ready(function() {
  $('#txtEmail').on('blur', function() {
    $(this).mailcheck({
      suggested: function(element, suggestion) {
        $('#spnSuggest').show();
        $('#spnSuggest').html("Did you mean '" + suggestion.full + "'?");
      },
      empty: function(element) {
         $('#spnSuggest').hide();
      }
     });
  });
});​
//Code Ends
See result below.



The included default domains are: yahoo.com, google.com, hotmail.com, gmail.com, me.com, aol.com, mac.com, live.com, comcast.net, googlemail.com, msn.com, hotmail.co.uk, yahoo.co.uk, facebook.com, verizon.net, sbcglobal.net, att.net, gmx.com, and mail.com.

The Mailcheck jQuery plugin uses the defaults to a list of top email domains if the domain option isn't provided. You can also provide list of domains based on the distribution of your users.

Below is the jQuery code that defines list of own domains. So now the plugin will only suggest for these 3 domains.
//Code Starts
var domains = ['hotmail.com', 'gmail.com', 'yahoo.com'];
$('#txtEmail').on('blur', function() {
    $(this).mailcheck({
      domains: domains,
      suggested: function(element, suggestion) {
        $('#spnSuggest').show();
        $('#spnSuggest').html("Did you mean '" + suggestion.full + "'?");
      },
      empty: function(element) {
         $('#spnSuggest').hide();
      }
     });
  });
//Code Ends
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Thursday, March 15, 2012

Validate Credit Card using jQuery Plugin

Have you ever come across a situation where you need to validate the credit card? Well, there is a good news now. There is a new plugin jQuery Credit Card Validator created by Pawel Decowski, which detects and validates credit card numbers. It’ll tell you the detected credit card type and whether the number length and Luhn checksum are valid for the type of card.

How to use it?
$('#cc_number').validateCreditCard(function(result)
{
    alert('CC type: ' + result.card_type
      + '\nLength validation: ' + result.length_valid
      + '\nLuhn validation: + result.luhn_valid');
});

How it works?

jQuery Credit Card Validator is written in CoffeeScript and (surprise, surprise!) is a jQuery plugin. It attaches to the input event (with a fallback to the keyup event) and, every time the number in the input field changes, it calls a function defined by you. It passes a single parameter to the function — an object with 3 properties:
  • card_type — an object with the below properties, or null if card type unknown
  • name — one of the strings describing the card type, eg visa
  • pattern — regular expression used to match the card type, eg /^4/
  • length — an array of valid lengths for the card type, eg [13, 16]
  • length_valid — true if the number length is valid, false otherwise
  • luhn_valid — true if the Luhn checksum is correct, false otherwise

Supported Cards

Below is the list of supported cards.
  • American Express — amex
  • Diners Club Carte Blanche — diners_club_carte_blanche
  • Diners Club International — diners_club_international
  • Diners Club United States & Canada — diners_club_us_and_ca
  • Discover Card — discover
  • JCB — jcb
  • Laser — laser
  • Maestro — maestro
  • MasterCard — mastercard
  • Visa — visa
  • Visa Electron — visa_electron
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Thursday, March 1, 2012

Date validation for "MM/YYYY" using jQuery

You may done validation for "dd/mm/yyyy" format but today I need to do validation for "MM/YYYY" format. The end user will input the date in textbox and I need to validate the date. Below jQuery code validates the date using regular expression in "MM/YYYY" format only using jQuery.


jQuery Code:
$(document).ready(function() {
  $('#txtDate').blur(function() {
      if(validateDate('txtDate'))
      {
          alert('Date is valid');
      }
      else
      {
          alert('Invalid Date!!!');
      }
   });
});

//Functions Starts
function validateDate(txtDate){
   var txtVal = document.getElementById(txtDate).value;
   var filter = new RegExp("(0[123456789]|10|11|12)([/])([1-2][0-9][0-9][0-9])");
   if(filter.test(txtVal))
      return true;
   else
     return false;
}​
//Functions Ends
//
The above code validates the date for year 1000-2999. Don't forget to set the maxlength of text box to 7.

See result below:

(Note: You can also see the jQuery code and HTML code by clicking on the buttons given below.)



Also read "Validate Date using jQuery"

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Monday, January 23, 2012

End Date should not be less than Start Date using jQuery Date Picker

How many times you have seen this message on websites? OR as a programmer, you should have implemented this very common date validation which is "End Date should not be less than Start Date". Gone those days where you write long java script functions for date validation and alert/show a error message on screen. It will be a nice feature where you don't allow end user to make mistake.

Earlier I had posted about Validate Date format, Validate Date using jQuery, Validate email address and Validate Phone numbers. And in this post, find how to make "End Date should not be less than Start Date" using jQuery and jQuery UI Datepicker.

Read my series of articles about jQuery UI Datepicker.

Required Resources:
1. jQuery
2. jQuery UI and jQuery UI CSS

Okay, so there are mainly 2 kind of validation conditions which are,
  1. Start date should not greater than end date.
  2. End date should not less then start date.
So let's put 2 textboxes "txtFromDate" and "txtToDate" and assign Date picker to it. With jQuery UI Date picker, there is an event "onSelect" which fires when any date is selected. So using this event, set the date range for other date pickers.

For example, when from date is selected, then using this "onSelect" event we will set the "minDate" attribute of "txtToDate" textbox to the selected date in "txtFromDate". What it does is that, dates less than the selected from date will be disabled in "txtToDate" textbox. And same way set the "MaxDate" attribute for "txtFromDate" in onSelect event of "txtToDate" textbox. Below is the complete jQuery code.
$(document).ready(function(){
    $("#txtFromDate").datepicker({
        numberOfMonths: 2,
        onSelect: function(selected) {
          $("#txtToDate").datepicker("option","minDate", selected)
        }
    });
    $("#txtToDate").datepicker({ 
        numberOfMonths: 2,
        onSelect: function(selected) {
           $("#txtFromDate").datepicker("option","maxDate", selected)
        }
    });  
});
"numberOfMonths" attribute allows to display multiple months in date picker. Read here about all the attribute of jQuery UI Datepicker.

See result below.
See Complete Code
Okay, this is interesting. But there is one more important condition which is also needed.
  1. Start date should not be greater than today's date.
Along with, there is one more functionality which you must have seen like many websites like flight booking, railway booking where there is a limit for To Date as well. For example, in India train ticket booking is only possible for next 90 days from the current date.

Okay so let's see that how we can implement these 2 conditions as well using jQuery UI DatePicker.

jQuery UI DatePicker provides attributes "MinDate" and "MaxDate" which allows to set minimum permissible date and maximum permissible date. So when "minDate" attribute is set to 0, then past dates will become disable from current date. And set "maxDate" to "+90D" which will make all the future dates disable except 90 days from current date. See below jQuery code. In this example, I have set "maxDate" to 60 days plus only.
$(document).ready(function(){
    $("#txtFromDate").datepicker({
        minDate: 0,
        maxDate: "+60D",
        numberOfMonths: 2,
        onSelect: function(selected) {
          $("#txtToDate").datepicker("option","minDate", selected)
        }
    });
    $("#txtToDate").datepicker({ 
        minDate: 0,
        maxDate:"+60D",
        numberOfMonths: 2,
        onSelect: function(selected) {
           $("#txtFromDate").datepicker("option","maxDate", selected)
        }
    });  
});
See result below.
See Complete Code
One advice: If you are still using Java Script, stop using it and switch to jQuery.

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Saturday, February 26, 2011

Download jQuery Validation Plugin Cheat Sheet

jQuery does not have any inbuilt form validation mechanism to do client side validation. But there is a very popular plugin "Validation" plugin, which helps to do validation. It is one of the most powerful, easy to use and popular plugin.

This jQuery plugin makes simple clientside form validation trivial, while offering lots of option for customization. That makes a good choice if you’re building something new from scratch, but also when you’re trying to integrate it into an existing application with lots of existing markup.
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...