Mask and Validate a DD/MM/YYYY DATE

Hi. I saw many scripts that mask a field with a date mask, but it's not what i want.
I want a function that uses a mask and a validate method together. Look at this example:
First I type the number 3
3_/__/____
so...when I press the second key... with a number between 2 and 9 the event break the type and allow to type only 0 and 1...

so when i type 0 or 1
31/__/____

and so on... the function is called all the time a  key is pressed and mask and at the same time checks if that character is VALID..

Someone have a script that do that? or something like that...it's very important to me.. and urgent. thank's Emu.
emu10k1Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

archrajanCommented:
0
GwynforWebCommented:
<script>
function validDate(obj){
 date=obj.value
if (/[^\d/]|(\/\/)/g.test(date))  {obj.value=obj.value.replace(/[^\d/]/g,'');obj.value=obj.value.replace(/\/{2}/g,'/'); return }
if (/^\d{2}$/.test(date)){obj.value=obj.value+'/'; return }
if (/^\d{2}\/\d{2}$/.test(date)){obj.value=obj.value+'/'; return }
if (!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(date)) return

 test1=(/^\d{1,2}\/?\d{1,2}\/\d{4}$/.test(date))
 date=date.split('/')
 d=new Date(date[2],date[1]-1,date[0])
 test2=(1*date[0]==d.getDate() && 1*date[1]==(d.getMonth()+1) && 1*date[2]==d.getFullYear())
 if (test1 && test2) return true
 alert("Invalid date")
 obj.select();
 obj.focus()
 return false
}
</script>


<body>
<p>Date1: <input type="text" name="startDate" size="9" maxLength="10"
onkeyup="validDate(this)"  onblur="validDate(this)"> </p>
</body>
</html>
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
GwynforWebCommented:
emu10k1 , ah I see I have not answered the question, I do mask and validate though but not as you wish
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

devicCommented:
>>so...when I press the second key... with a number between 2 and 9 the event break the type and allow to type only 0 and 1...

it can not be done...

where do you know what I will type in month area? maybe the month will be february and it has only 29 days?
0
GwynforWebCommented:
......now there is a challenge. :-)
0
devicCommented:
ok if you change order (yyyy/mm/dd), or it will jump every time between "fiedls"  then it's possible.
else only with magic ;)
0
suramsureshbabuCommented:
its a tough nut to crack
0
suramsureshbabuCommented:
it needs a lot of scripting to be done but the date format should be in yyyy/mm/dd format
it is possible
0
archrajanCommented:
SEE THIS
<HTML>
      <HEAD>
      <TITLE>Key Input Test</TITLE>
      <script language="JavaScript">
var keybYN = new keybEdit('yn','Valid values are \'Y\' or \'N\'.');
var keybNumeric = new keybEdit('01234567890','Numeric input only.');
var keybAlpha = new keybEdit('abcdefghijklmnopqurstuvwxy ','Alpha input only.');
var keybAlphaNumeric = new keybEdit('abcdefghijklmnopqurstuvwxy01234567890 ','Alpha-numeric input only.');
var keybDecimal = new keybEdit('01234567890.','Decimal input only.');
var keybDate =  new keybEdit('01234567890/','Date input only');;
var keybYNNM = new keybEdit('yn');
var keybNumericNM = new keybEdit('01234567890');
var keybAlphaNM = new keybEdit('abcdefghijklmnopqurstuvwxy');
var keybAlphaNumericNM = new keybEdit('abcdefghijklmnopqurstuvwxy01234567890');
var keybDecimalNM = new keybEdit('01234567890.');
var keybDateNM = new keybEdit('01234567890/');;

function keybEdit(strValid, strMsg) {
      /*      Function:            keybEdit
            Creation Date:      October 11, 2001
            Programmer:            Edmond Woychowsky
            Purpose:            The purpose of this function is to be a constructor for
                                    the keybEdit object.  keybEdit objects are used by the
                                    function editKeyBoard to determine which keystrokes are
                                    valid for form objects.  In addition, if an error occurs,
                                    they provide the error message.
                                    
                                    Please note that the strValid is converted to both
                                    upper and lower case by this constructor.  Also, that
                                    the error message is prefixed with 'Error:'.
                                    
                                    The properties for this object are the following:
                                          valid      =      Valid input characters
                                          message      =      Error message
                                          
                                    The methods for this object are the following:
                                          getValid()      =      Returns a string containing valid
                                                                  characters.
                                          getMessage()=      Returns a string containing the
                                                                  error message.

            Update Date:      Programmer:                  Description:
      */

      //      Variables
      var reWork = new RegExp('[a-z]','gi');            //      Regular expression\

      //      Properties
      if(reWork.test(strValid))
            this.valid = strValid.toLowerCase() + strValid.toUpperCase();
      else
            this.valid = strValid;

      if((strMsg == null) || (typeof(strMsg) == 'undefined'))
            this.message = '';
      else
            this.message = strMsg;

      //      Methods
      this.getValid = keybEditGetValid;
      this.getMessage = keybEditGetMessage;
      
      function keybEditGetValid() {
      /*      Function:            keybEdit
            Creation Date:      October 11, 2001
            Programmer:            Edmond Woychowsky
            Purpose:            The purpose of this function act as the getValid method
                                    for the keybEdit object.  Please note that most of the
                                    following logic is for handling numeric keypad input.

            Update Date:            Programmer:                  Description:
      */

            return this.valid.toString();
      }
      
      function keybEditGetMessage() {
      /*      Function:            keybEdit
            Creation Date:      October 11, 2001
            Programmer:            Edmond Woychowsky
            Purpose:            The purpose of this function act as the getMessage method
                                    for the keybEdit object.

            Update Date:      Programmer:                  Description:
      */
      
            return this.message;
      }
}




void function editKeyBoard(objForm, objKeyb) {
      /*      Function:            editKeyBoard
            Creation Date:      October 11, 2001
            Programmer:            Edmond Woychowsky
            Purpose:            The purpose of this function is to edit edit keyboard input
                                    to determine if the keystrokes are valid.
      
            Update Date:            Programmer:                  Description:
      */

      strWork = objKeyb.getValid();
      strMsg = '';                                          // Error message
      blnValidChar = false;                              // Valid character flag

      // Part 1: Validate input
      if(!blnValidChar)
            for(i=0;i < strWork.length;i++)
                  if(window.event.keyCode == strWork.charCodeAt(i)) {
                        blnValidChar = true;

                        break;
                  }

      // Part 2: Build error message
      if(!blnValidChar) {
            if(objKeyb.getMessage().toString().length != 0)
                  alert('Error: ' + objKeyb.getMessage());

            window.event.returnValue = false;            // Clear invalid character
            objForm.focus();                                    // Set focus
      }
}

void function setEvents() {
      document.all.txtYN.onkeypress = new Function('editKeyBoard(this,keybYN)');
      document.all.txtNumeric.onkeypress = new Function('editKeyBoard(this,keybNumeric)');
      document.all.txtAlpha.onkeypress = new Function('editKeyBoard(this,keybAlpha)');
      document.all.txtAlphaNumeric.onkeypress = new Function('editKeyBoard(this,keybAlphaNumeric)');
      document.all.txtDecimal.onkeypress = new Function('editKeyBoard(this,keybDecimal)');
      document.all.txtDate.onkeypress = new Function('editKeyBoard(this,keybDate)');
}
      </script>
      </HEAD>
      <body onLoad="JavaScript:setEvents()">
            <TABLE WIDTH=100% BORDER=0 CELLSPACING=1 CELLPADDING=1>
                  <TR>
                        <TD align="right">YN:&nbsp</TD>
                        <TD align="left"><INPUT type="text" id=txtYN name=txtYN></TD>
                  </TR>
                  <TR>
                        <TD align="right">Numeric:&nbsp</TD>
                        <TD align="left"><INPUT type="text" id=txtNumeric name=txtNumeric></TD>
                  </TR>
                  <TR>
                        <TD align="right">Alpha:&nbsp</TD>
                        <TD align="left"><INPUT type="text" id=txtAlpha name=txtAlpha></TD>
                  </TR>
                  <TR>
                        <TD align="right">AlphaNumeric:&nbsp</TD>
                        <TD align="left"><INPUT type="text" id=txtAlphaNumeric name=txtAlphaNumeric></TD>
                  </TR>
                  <TR>
                        <TD align="right">Decimal:&nbsp</TD>
                        <TD align="left"><INPUT type="text" id=txtDecimal name=txtDecimal></TD>
                  </TR>
                  <TR>
                        <TD align="right">Date:&nbsp</TD>
                        <TD align="left"><INPUT type="text" id=txtDate name=txtDate></TD>
                  </TR>
            </TABLE>
      </body>
</HTML>
0
archrajanCommented:
the above script needs a lot of modifications though
use document.formname instead of document.all
0
devicCommented:
>>>the above script needs a lot of modifications though
sure, also it will never work, as it will emu10k1...

and the problem is not that we don't know how to check input box....
here is just a logical error....
archrajan, you can paste here whole internet and it will not help...
0
archrajanCommented:
devic thanks for commenting about me and my code
0
archrajanCommented:
something is always better than nothing :)
0
emu10k1Author Commented:
archrajan i will check your code  and i will post my considerations.. one day more .. because i broke my right hand.. its difficulty to work in this way.. wait one more day. thanks all. Emu
0
StormyWatersCommented:
This will do as you originally specified, only YYYY/MM/DD format. I can't do DD/MM/YYYY format without some magic.

To archajan, I can't really understand what that code accomplishes within this context. I haven't taken a close look, though.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Masked Date</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script>

/* This script is (C) Ryan Pearl 2004. Reeased into public domain.
   This comment MUST remain intact.
 */

var splitter = '/';
var lengths = [4,2,2];

var maxlength = eval(lengths.join('+')) + lengths.length-1;

function leap_year(year) {
      return year%4==0&&year%100!=0||year%400==0;
}
function positionCursor(input, position) {
  if(input.createTextRange) {
    var range = input.createTextRange();
      range.collapse(true);
    range.moveStart('character', position);
    range.select();
  } else {
    input.focus();
    input.setSelectionRange(position,position);  
  }
}

function left_pad(str, padding, to) {
  while(str.length < to) {
    str += padding;
  }
  return str;
}

function do_fancy_stuff(ob) {
 
  var val = ob.value.replace(/ /g, '').split(splitter);
  var pos = 0, checking = -1;
  var bad_val = /[^0-9]/g;
 
  while(val.length < 3) { //ensure proper number of 'fields'.
    val[val.length] ='';
      pos--; //realign things (because the reason this would happen is someone deleting a splitter char.
  }
 
  for(var i = 0; i < val.length; i++) {
    if(bad_val.test(val[i]) && val[i].replace(' ', '') != '') { //field contains a bad value.
        val[i] = val[i].substr(0, val[i].length-1); //chop off the last char.
      }
    pos += val[i].length; //increment the position by the length of the current field
      if(val[i].length == lengths[i]) {
        pos++; //increment it one more if it fills the whole thing, bypassing splitter char.
        checking++; //current field we're checking.
      }
      if(val[i].length > lengths[i]) { //split it up between fields if the user has gone back and then typed again.
        val[i+1] = val[i].substr(lengths[i]) + val[i+1];
        val[i] = val[i].substr(0,lengths[i]);
        pos++;
      }
  }
 
  //Validate date.
  if(checking == 1) {
    var check_month = /^[0 ][0-9]|1[0-2]$/;
      if(!check_month.test(val[1])) {
        val[1] = val[1].substr(0, val[1].length-1);
        val[1] += ' ';
        pos--;
      }
  }
  if((checking == 1 && val[2].length > 0) || checking == 2) {
    var numdays = new Array('31', leap_year(parseInt(val[0]))?'29':'28', '31', '30', '31', '30', '31', '31', '30', '31', '30', '31');
    var d = numdays[(1*val[1])-1];
    var check_day = new RegExp('^([0-'+(d.charAt(0)-1)+' ][0-9]?|'+d.charAt(0)+'[0-'+d.charAt(1)+']?)$');
    if(!check_day.test(val[2])) {
      val[2] = val[2].substr(0, val[2].length-1);
      pos--;
    }
  }
 
  //Pad the string.
  for(var i = 0; i < val.length; i++) {
    val[i] = left_pad(val[i], ' ', lengths[i]);
  }
  //Join it all together.
  ob.value = val.join(splitter);
 
  //We can't just rely on the maxlength because people wouldn't be able to type then!
  if(ob.value.length > maxlength) ob.value = ob.value.substr(0, maxlength);
 
  //position the cursor at our calculated spot.
  positionCursor(ob, pos);
}
</script>
</head>

<body onload="">
<form name="form1" id="form1" method="post" action="">
  <input type="text" name="date" value="    /  /  " onkeyup="do_fancy_stuff(this);" maxlength="11">
</form>
</body>
</html>
0
archrajanCommented:
you can perform even mm/dd/yyyy format and dd/mm/yyyy validation by customizing the script
0
StormyWatersCommented:
Yes. But that wasn't the question.
0
GwynforWebCommented:
I do not see the problem with the dd/mm/yyyy format, you just validate it as beeing a possibly valid date, eg not allowing 30 days for february and final validating when the final digit of the year is typed.
0
GwynforWebCommented:
.. I also wish peole would learn how to use the date object to do validation, it makes for much more professional/compact code
0
StormyWatersCommented:
I was just answering his specific question. I don't think this is the best way to do it, but this is what he wants.
0
StormyWatersCommented:
Small correction :)

this:
  if(checking == 1) {
    var check_month = /^[0 ][0-9]|1[0-2]$/;

should be:
  if(checking == 0 && val[1].length > 0 || checking == 1) {
    var check_month = /^([0 ][0-9]?|1[0-2]?)$/;
0
GwynforWebCommented:
..I was refering to the specific question here and the posted code for other sources which is dreadful. In general I think the whole concept of masking the date like this also dreadful.
0
GwynforWebCommented:
...if you are going to mask the date in anyway you should  3 seperate boxes, or preferable 3 selects.
0
StormyWatersCommented:
Please don't just leave this question open. If there is a viable solution, please accept an answer. If there isn't, ask for a refund in community support, or delete the question. Don't just abandon it.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.