Wednesday 10 April 2013

How to validate date and time in Sencha Touch 2

Sencha Touch 2 provides lot of utility methods for managing date and time information using Ext.DateExtras Object. Ext.DateExtras class will not be included by default in Sencha Touch 2 Application. You need to add this class as the requires in which you wish to use them (Either Controller or Application). Inorder to use Ext.DateExtras, you need to use Ext.Date Object.

We are going to use isValid() function for validating date using the passed values. This might be handy when you are checking user input date in form. This method accepts the following parameters
  • year : 4-digit year.
  • month : 1-based month-of-year.
  • day : Day of month.
  • hour : Hour (optional).
  • minute : Minute (optional).
  • second : Second (optional).
  • millisecond : Millisecond (optional).
And It returns Boolean, true  if the passed parameters do not cause a Date "rollover", false otherwise
Ext.application({

    requires: [
        'Ext.DateExtras'
    ],
    name: 'MyApp',

    launch: function() {
       console.log('Validate Date and Time:');
       var valid = Ext.Date.isValid('2013','10','31');
       console.log('2013-10-31: ',valid);
       var valid = Ext.Date.isValid('2013','02','30');
       console.log('2013-02-30: ',valid);
       var valid = Ext.Date.isValid('2013','04','31');
       console.log('2013-04-31: ',valid);
    }
});

When i run this code in Google Chrome, Following are the output

Validate Date and Time:
2013-10-31:  true
2013-02-30:  false
2013-04-31:  false

Hope, you enjoyed this Post.

No comments:

Post a Comment