Link to home
Start Free TrialLog in
Avatar of zachvaldez
zachvaldezFlag for United States of America

asked on

date masking jquery

I used this date making function
$(document).ready(function(){

$('.date').mask('00/00/0000');

})

but one user wants the ability not to add the trailing 0.
for example
1/10/2015
or 1/1/2015..

how can I modify this function?
Avatar of Big Monty
Big Monty
Flag of United States of America image

i assume you're using this plug-in...

taken from their docs:


On-the-fly mask change
var options =  {onKeyPress: function(cep, e, field, options){
  var masks = ['00000-000', '0-00-00-00'];
    mask = (cep.length>7) ? masks[1] : masks[0];
  $('.crazy_cep').mask(mask, options);
}};

$('.crazy_cep').mask('00000-000', options);

i think what you want is:

$(document).ready(function(){

var options =  {onKeyPress: function(cep, e, field, options){
  var masks = ['00/00/000', '0/0/0000'];
  var val = new Date();
  if isDate( cep ) {
      val = cep;
      mask = (val.getDay().length <= 1) ? masks[1] : masks[0];
  }
  $('.date').mask(mask, options);
}};

$('.date').mask('00/00/0000', options);

});

function isDate( d ) {
   return d instanceof Date && !isNaN(date.valueOf());
}

Open in new window

I assume you mean a leading 0, not trailing 0 - otherwise you get a completely different date and it makes no sense.

You can pass a callback in to make certain digits optional:

$('.date').mask('0Z/0Z/0000', {
	translation: {
		'Z': { pattern: /[0-9]/, optional: true }
	}
});

Open in new window

Avatar of zachvaldez

ASKER

while testing, a user can enter data like 14/32/2018 or 22/14/2050..
what is the way to validate so dates are more realistic. Would like to disallow entries  year > 12 and days > 31..
HI, I'm looking at this because the short code appeals to me. However when implementing the class 'date , when typing 112015 to convert it to 1/1/2015 , it resulted to 11/20/15...
HI Big monty. I'm testing your solution. Thanks, it's looking for a'(' after isDate.. it could be typo. Please correct.
change

if isDate( cep ) {

to

if (isDate( cep ) ) {
Hi Big, what is the implementation of your solution. Should the call it be added to the cssclass?
I'm getting error 'object does not support 'charAt'??
also an error 'mask' undefined..
try the following:

$(document).ready(function(){

var options =  {onKeyPress: function(cep, e, field, options){
  var masks = ['00/00/000', '0/0/0000'];
  var mask = '00/00/000';
  var val = new Date();
  if isDate( cep ) {
      val = cep;
      mask = (val.getDay().length <= 1) ? masks[1] : masks[0];
  }
  $('.date').mask(mask, options);
}};

$('.date').mask('00/00/0000', options);

});

function isDate( d ) {
   return d instanceof Date && !isNaN(date.valueOf());
}

Open in new window

Thanks Big! I'll test this tomorrow.
Big, there is an error in this line
if isDate( cep ) {

specifically '{'
this is how I use the html
<asp:TextBox ID="txtB" runat="server" CssClass="form-control date" data-mask='00/00/0000' data-mask-clearifnotmatch="true"></asp:TextBox>

would this method change?
change

if isDate( cep ) {

to

if (isDate( cep ) ) {
I did that but how would I apply it to the HTML and what change? Right now I have this
$('.date').mask('00/00/0000') but Id like also to have another function
like $('date).mask('0/0/0000') or $(date).mask(0/00/0000)
to handle possible ways of entering date.
the code I provided was straight from their docs, and it changes the mask on the fly, so no HTML modifications should be needed
Thanks Big,
>>>no HTML modifications should be needed..
So this HTML I have should I modify it based on the jquery...?
<asp:TextBox ID="txtB" runat="server" CssClass="form-control date" data-mask='00/00/0000' data-mask-clearifnotmatch="true"></asp:TextBox>

would b
chris,
How to use your solution?

>>>$('.date').mask('0Z/0Z/0000', {
      translation: {
            'Z': { pattern: /[0-9]/, optional: true }
      }
});
So this HTML I have should I modify it based on the jquery...?

i don't believe so, you have a class called "date" on the text box and you're referencing the field in the jquery by the "date" class
so which one should be remove or should be use?
leave it as is
If I leave,the way it is, user is forced to follow the mm/dd/yyyy pattern.
you may need to use the Request Attention feature then, as I've only used that feature on a very basic level
I think a regular expression on dates may solve this.
I put in a "Request Attention" request so some additional experts will be notified to try to help. In the meantime, I'll continue tinkering around on my end
Personally, I think you're over complicating it.

Have a look at this - I removed the option to have optional digits, and instead added a place-holder - this is considered normal, default behaviour so your users will instantly know what's expected.

I've added in an onComplete() method that you can use to add validation if needed.

Have a play: http://jsfiddle.net/ChrisStanyon/1b9frjn4/
Chris,
  Thanks, I don't see any placeholder in your link and how to use it.
I tried to type 10102000 hoping will format it to 10/10/2000 but did not.
Not sure why it doesn't work. It works fine for me. It shows the place holder and formats the date correctly.

Here's the code:

$('#datemask').mask('00/00/0000', {
    onComplete: function(value) {
        var parts = value.split("/");
        var myDate = new Date(parts[2] + '-' + parts[1] + '-' + parts[0]);
        $('#response').html( myDate.toString() );
    },
    placeholder: "dd/mm/yyyy"
});

Open in new window

I use IE. Does it matter?
Ahh - right. It' not the code that doesn't work. IE seems to block jsfiddle.net from loading the mask plugin directly from github. You'll need to try my code on your own page, rather than using the fiddle.
Ok, I'll try that. Your opinion only-- Can I recommend to someone to use fiddle to learn programming? Are there resources there that can help someone to improve skills?
Here is my current  textbox... code for example
<div class="col-md-1">
                        <asp:TextBox ID="TextBox8" runat="server" CssClass="form-control date" data-mask='00/00/0000' data-mask-clearifnotmatch="true"></asp:TextBox>
                    </div>

How woyuld I use the jquery?
JSFiddle won't teach you how to program - it's a simple sandbox / scratch pad that you can use to test your code on and share it with others.

For learning to develop, there's a ton of great websites on the net - it just depends on what you want to learn, how you learn best, and how much time and money you have.
That code looks like it's giving your textbox an ID of TextBox8, so just use that:

$('#TextBox8').mask('00/00/0000', {
    onComplete: function(value) {
        var parts = value.split("/");
        var myDate = new Date(parts[2] + '-' + parts[1] + '-' + parts[0]);
        $('#response').html( myDate.toString() );
    },
    placeholder: "dd/mm/yyyy"
});

Open in new window


Here's a tip - jQuery is what's called client-side code, which means it runs purely in your browser - it has no clue about your server. ASP is a server-side script - the 2 live on different sides of the same coin.

The code you posted is NEVER seen by jQuery. To see what jQuery sees, look at the source of your page in your browser.
First of there a many textboxes in the form that requires formatting dates. How can I apply this as a class to all of it I want to format.
Secondly,
 It worked in te app but I was able to type 11/11/111 and  90/90/9000  and got away with it. can the placeholder be MM/dd/yyyy instead of dd/mm/yyyy?
look at the source of your page in your browser. >>> Isn't this the link I place on the page?
I think it should be a class rather than an ID?
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Also the placeholder does not show.. I research it , it does not work for IE.
It suggested to use modernizer but no clue how to use that> thanks
That's the joy of Internet Explorer !!

Either look from a masking plugin that will work for ie, or just use a label instead.
I found a plugin as you suggested and it works!
what should I do to make sure what was entered is a date? not 90/90/9000 and others.
Depends on the plug-in you've found. I think you're confusing a mask plugin with a validation plugin. Once your user has entered a date (according to the mask), then you'll need to retrieve that date and run it against some validation. Your new mask plugin may be able to that, but if not you'll need to validate it separately.
Excellent!