?
Solved

Mask and Validate a DD/MM/YYYY DATE

Posted on 2004-11-26
24
Medium Priority
?
1,957 Views
Last Modified: 2010-05-18
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.
0
Comment
Question by:emu10k1
  • 7
  • 6
  • 5
  • +3
24 Comments
 
LVL 25

Expert Comment

by:archrajan
ID: 12683249
0
 
LVL 31

Accepted Solution

by:
GwynforWeb earned 1000 total points
ID: 12683447
<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
 
LVL 31

Expert Comment

by:GwynforWeb
ID: 12683472
emu10k1 , ah I see I have not answered the question, I do mask and validate though but not as you wish
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 25

Expert Comment

by:devic
ID: 12683529
>>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
 
LVL 31

Expert Comment

by:GwynforWeb
ID: 12683791
......now there is a challenge. :-)
0
 
LVL 25

Expert Comment

by:devic
ID: 12683818
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
 
LVL 7

Expert Comment

by:suramsureshbabu
ID: 12683825
its a tough nut to crack
0
 
LVL 7

Expert Comment

by:suramsureshbabu
ID: 12683984
it needs a lot of scripting to be done but the date format should be in yyyy/mm/dd format
it is possible
0
 
LVL 25

Expert Comment

by:archrajan
ID: 12688327
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
 
LVL 25

Expert Comment

by:archrajan
ID: 12688331
the above script needs a lot of modifications though
use document.formname instead of document.all
0
 
LVL 25

Expert Comment

by:devic
ID: 12688350
>>>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
 
LVL 25

Expert Comment

by:archrajan
ID: 12688650
devic thanks for commenting about me and my code
0
 
LVL 25

Expert Comment

by:archrajan
ID: 12688652
something is always better than nothing :)
0
 

Author Comment

by:emu10k1
ID: 12690572
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
 
LVL 13

Expert Comment

by:StormyWaters
ID: 12691170
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
 
LVL 25

Expert Comment

by:archrajan
ID: 12691327
you can perform even mm/dd/yyyy format and dd/mm/yyyy validation by customizing the script
0
 
LVL 13

Expert Comment

by:StormyWaters
ID: 12691388
Yes. But that wasn't the question.
0
 
LVL 31

Expert Comment

by:GwynforWeb
ID: 12691569
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
 
LVL 31

Expert Comment

by:GwynforWeb
ID: 12691581
.. I also wish peole would learn how to use the date object to do validation, it makes for much more professional/compact code
0
 
LVL 13

Expert Comment

by:StormyWaters
ID: 12691634
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
 
LVL 13

Expert Comment

by:StormyWaters
ID: 12691852
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
 
LVL 31

Expert Comment

by:GwynforWeb
ID: 12692508
..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
 
LVL 31

Expert Comment

by:GwynforWeb
ID: 12692559
...if you are going to mask the date in anyway you should  3 seperate boxes, or preferable 3 selects.
0
 
LVL 13

Expert Comment

by:StormyWaters
ID: 12880726
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

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In Part 1 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7849-Hex-Maze.html) we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question