Solved

Check date entered on a web page against a list of dates in a text file

Posted on 2011-09-15
22
332 Views
Last Modified: 2012-06-22
I need a simple solution to a problem

I want a user to be able to enter a date on a web page.

I then want to be able to compare the date entered by the user against a list of dates stored in a text file on the server (max of 50 or so dates)

If the date matches a date in the list then I want to be able to print "date already taken" next to the date input box
If there is no match of the date entered with a date in the list then I want to display "date available" next to the input.

I want a simple solution to this - I'm thinking of JavaScript to read a simple text file containing the dates, one date per line. I can easily maintain this file manually.  

I don't want a SQL solution (far too complex for me to implement and maintain



0
Comment
Question by:KCTS
  • 10
  • 7
  • 5
22 Comments
 
LVL 75

Accepted Solution

by:
Michel Plungjan earned 500 total points
ID: 36545895
Make the date file a js file

//---- JS FILE
var datesTaken=[
"Oct 8, 2011",
"Oct 18, 2011",
"Oct 28, 2011",
"Nov 8, 2011"
]; // notice no comma after the last
// -- no need to change below this
var dateArray = [];
for (var i=0, n=datesTaken.length;i<n;i++) {
  dateArray[i]=Date.parse(datesTaken[i])
}
function isDateTaken(dateString) {
  var date = Date.parse(dateString);
  for (var i=0, n=dateArray.length;i<n;i++) {
    if (date === dateArray[i]) return true;
  }
  return false;
}

Open in new window


and in your web page have

alert(isDateTaken("Oct 18, 2011"))

Open in new window

0
 
LVL 63

Expert Comment

by:Zvonko
ID: 36545903
Store that text file as an .js file that contains the array of the dates you maintain.
The script load that array and compares accordingly.
Enter the dates in this format: MM/DD/YYYY
That is the format that JavaScript understands without conversion.
For example if your text file has thsi line:

arrTakenDates=["09/13/2011","09/14/2011","09/15/2011"];

Then the script can crate JavaScript Date like this:

var theDate = new Date(arrTakenDates[0]);

You see?

0
 
LVL 63

Expert Comment

by:Zvonko
ID: 36545906
Upps :-)
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36545914
:)
0
 
LVL 70

Author Comment

by:KCTS
ID: 36545977
Ideally I would like the dates in a separate file so it can be maintained easier and the dates are not obvious is someone does a 'view source'

Does the above code put the appropriate wording on the page ?
 
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36546190
My suggestion puts the dates and the function testing the input date into an external file. If you want more code, please show the form in question
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36546196
My suggestion puts the dates and the function testing the input date into an external file. If you want more code, please show the form in question
0
 
LVL 70

Author Comment

by:KCTS
ID: 36546382
@ OK - i'm with you now - I'll give it a try
0
 
LVL 70

Author Comment

by:KCTS
ID: 36546473
I'm not sure how I'm supposed to get this to work - I've attached the code for the form on which I want to use this (It was created with the EmailMe form builder).

There is a box into which the user is asked to enter a date (element_6)

when they have entered a date, then I want to show some text next to the box to show if the date is available or not


<!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>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Enquiry Form</title>
</head>

<body>




<link rel="stylesheet" type="text/css" href="http://www.emailmeform.com/builder/styles/dynamic.php?t=post" />
<link rel="stylesheet" type="text/css" href="http://www.emailmeform.com/builder/theme_css/ZB5qHSzTA0" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined'){
    document.write(unescape("%3Cscript src='http://www.emailmeform.com/builder/js/jquery-1.4.4.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<script type="text/javascript">
if (typeof $.ui == 'undefined'){
    document.write(unescape("%3Cscript src='http://www.emailmeform.com/builder/js/jquery-ui-1.7.2.custom.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>
<script type="text/javascript" src="http://www.emailmeform.com/builder/js/dynamic.php?t=post&t2=0&use_CDN=true"></script>
<form id="emf-form" enctype="multipart/form-data" method="post" action="http://www.emailmeform.com/builder/form/ZB5qHSzTA0" name="emf-form">
  <table style="text-align:left;" cellpadding="2" cellspacing="0" border="0" bgcolor="#FFFFFF">
    <tr>
      <td style="" colspan="2">
        <font face="Verdana" size="2" color="#000000"><b style="font-size:20px;">Enquiry</b><br />
        <label style="font-size:15px;">Please give brief details of your enquiry, We will then get back to you to discuss and answer any questions you may have.<br /></label><br /></font>
      </td>
    </tr>
    <tr valign="top">
      <td id="td_element_label_0" align="left">
        <font face="Verdana" size="2" color="#000000"><b>Your Name</b></font>
      </td>
      <td id="td_element_field_0" style="">
        <input id="element_0" name="element_0" value="" size="50" class="validate[optional]" type="text" />
        <div style="padding-bottom:8px;color:#000000;"></div>
      </td>
    </tr>
    <tr valign="top">
      <td id="td_element_label_1" align="left">
        <font face="Verdana" size="2" color="#000000"><b>Your Email Address</b></font>
      </td>
      <td id="td_element_field_1" style="">
        <input id="element_1" name="element_1" class="validate[optional,custom[email]]" value="" size="60" type="text" style="width: 311px" />
        <div style="padding-bottom:8px;color:#000000;"></div>
      </td>
    </tr>
    <tr valign="top">
      <td id="td_element_label_2" align="left">
        <font face="Verdana" size="2" color="#000000"><b>Telephone</b></font>
      </td>
      <td id="td_element_field_2" style="">
        <input id="element_2" name="element_2" value="" size="30" class="validate[optional]" type="text" />
        <div style="padding-bottom:8px;color:#000000;"></div>
      </td>
    </tr>
    <tr valign="top">
      <td id="td_element_label_6" align="left">
        <font face="Verdana" size="2" color="#000000"><b>Date of Wedding/Event<br />
        (if known/applicable)</b></font>
      </td>
      <td id="td_element_field_6" style="">
        <input id="element_6" name="element_6" value="" size="34" class="validate[optional]" type="text" style="width: 113px" />
        <div style="padding-bottom:8px;color:#000000;"></div>
      </td>
    </tr>
    <tr>
      <td colspan="2" align="left">
        <input name="element_counts" value="8" type="hidden" /> <input name="embed" value="forms" type="hidden" /><input value="Send Enquiry" type="submit" />
      </td>
    </tr>
  </table>
</form><script type="text/javascript">
//<![CDATA[
var EMF_Safari_Captcha = (function(){
        this.isChrome = (/chrome/.test(navigator.userAgent.toLowerCase()));
        this.isSafari = !this.isChrome && (/safari/.test(navigator.userAgent.toLowerCase()));
        this.process_captcha = function(){
                EMF_jQuery('a#captcha_code_refresh').trigger('click');
                get_valid_captcha();
        }
        this.firstTimeSession = true;
        this.safari_submit_session_form = function(){
                if (this.firstTimeSession) {
                                this.firstTimeSession = false;
                                EMF_jQuery("#safari_sessionform").submit();
                                setTimeout('process_captcha()',2000);
                }
        }
        return this;
})();
EMF_jQuery(function(){
        EMF_jQuery("#emf-form").validationEngine({
                validationEventTriggers:"blur",
                scroll:true
        });




        EMF_jQuery("#emf-form ul li").mousedown(highlight_field_on_mousedown);
        EMF_jQuery("#emf-form ul li input, #emf-form ul li textarea, #emf-form ul li select").focus(highlight_field_on_focus);

        var form_obj=EMF_jQuery("#emf-container form");
        if(form_obj.length>0 && form_obj.attr('action').indexOf('#')==-1){
                form_obj.attr('action', form_obj.attr('action')+document.location.hash);
        }

});

EMF_jQuery(window).load(function(){
        var parent_url = decodeURIComponent(document.location.hash.replace(/^#/, ''));
        XD.postMessage(get_frame_height(), parent_url, parent);
});

//]]>
</script>



</body>

</html>

Open in new window

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36547264
I'll look in a few hours. 6am here now so I just got up.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36547569
This is NOT simple to ADD - your emailmeform has its own validation and when I bind to the submit event, it seems the other validation is not happening.
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36547618
Here is the script as it would look on its own

DEMO HERE

<form onsubmit="return validate(this)">
    <input name="element_6" type="date" value="" />
    <input type="submit" />
</form>    
// This is in an external file
var datesTaken=[
"Oct 8, 2011",
"Oct 18, 2011",
"Oct 28, 2011",
"Nov 8, 2011"
]; // notice no comma after the last

// -- no need to change below this
var dateArray = [];
for (var i=0, n=datesTaken.length;i<n;i++) {
  dateArray[i]=Date.parse(datesTaken[i])
}
function isDateTaken(dateString) {
  var date = Date.parse(dateString);
  for (var i=0, n=dateArray.length;i<n;i++) {
    console.log(date+'\n'+dateArray[i]);
    if (date === dateArray[i]) return true;
  }
}
    
// -------- this could be inline ----
    function validate(theForm) {
       var date = new Date(theForm.element_6.value);
       if (isDateTaken(date)) {
         alert('Sorry, this date is not available');
         theForm.element_6.focus();
         return false;
       }
    }

Open in new window

0
 
LVL 63

Expert Comment

by:Zvonko
ID: 36547688
Sorry to jump again in but I have finished a version bound to submit button and would like to show here but it does basically the same as upper one.
My idea was to name the takenDates file like this:
<script type="text/javascript" src="jquery-ui-42.max.js"></script>

In that file is the line as I posted in my first comment.

The submit button needs the onClick:
<input value="Send Enquiry" type="submit" onClick="return checkDate(this)" />

And here i´s the function called by onClick:
function checkDate(theBtn){
  var fldDate = theBtn.form.element_6;
  var theDate = fldDate.value.replace(/(^\s*|\s*$)/g,"");
  if(theDate==""){
    alert("Enter Date");
	fldDate.focus();
	return false;
  }
  for(var i=0;i<arrTakenDates.length;i++){
    if(arrTakenDates[i]==theDate){
	  alert("Date taken.\nPlease take anoter Date.");
	  fldDate.focus();
	  return false;
    }
  }
  return true;  
}

Open in new window

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36547714
Zvonko - why on the submit button?

Why not onSubmit?

And in this case we can actually not use any of them it seems
0
 
LVL 63

Expert Comment

by:Zvonko
ID: 36547788
I did not test the onSubmit event handler because you stated that it yields a colusion. I did not check it. I checked only the onClick and that works.

Basicaly is my solely idea to name the dates file simelar to used jQuery files and so hide the source.
0
 
LVL 70

Author Comment

by:KCTS
ID: 36552295
Is there a way to have the message shown on the screen as soon as the date is entered ?
or if that not possible to have another button labelled check date (or similar).
I would like the user to know if the date is available BEFORE they submit the form.
0
 
LVL 70

Author Comment

by:KCTS
ID: 36552330
@mplungjan - I've had a look at your DEMO on ID: 36547618 and I think this could be made to work, however if its possible to implement a small change would be even better!

Would it be possible to have the date in the box in the UK standard DD/MM/YYYY format (it seems to be in the YYYY/MM/DD universal format at the moment.

0
 
LVL 70

Author Comment

by:KCTS
ID: 36552518
... and I'm still not sure how I can implement the check and as without submitting the form - can I just have a check date button and leave the current submit button as it is ?
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36553125
Why not show a calendar of available dates instead? Saves validating input and user frustration!
0
 
LVL 70

Author Comment

by:KCTS
ID: 36556316
I don't want to show a calendar as I don't want users to see how busy (or not) I am.

All I want to do is for the user to enter a date into a box and then have a message display if the date is taken or not -
It seemed like such a simple idea...
0
 
LVL 63

Expert Comment

by:Zvonko
ID: 36556372
The function that you put into onSubmit event handler you can do also in the onChange event handler for the date input field or on a separate button for date checking.

But a simple convenient function doing the doWhatImean() procedure is still in development <|:-)
0
 
LVL 75

Assisted Solution

by:Michel Plungjan
Michel Plungjan earned 500 total points
ID: 36556478
Here is my final example, tested with your form

Note I moved all code to the head and while testing, I removed the action
<!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>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Enquiry Form</title>
<link rel="stylesheet" type="text/css" href="http://www.emailmeform.com/builder/styles/dynamic.php?t=post" />
<link rel="stylesheet" type="text/css" href="http://www.emailmeform.com/builder/theme_css/ZB5qHSzTA0" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined'){
    document.write(unescape("%3Cscript src='http://www.emailmeform.com/builder/js/jquery-1.4.4.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<script type="text/javascript">
if (typeof $.ui == 'undefined'){
    document.write(unescape("%3Cscript src='http://www.emailmeform.com/builder/js/jquery-ui-1.7.2.custom.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>
<script type="text/javascript" src="http://www.emailmeform.com/builder/js/dynamic.php?t=post&t2=0&use_CDN=true"></script>

<script type="text/javascript">
// This could be in an external file
var datesTaken=[
"Oct 8, 2011",
"Oct 18, 2011",
"Oct 28, 2011",
"Nov 8, 2011"
]; // notice no comma after the last

// -- no need to change below this
var dateArray = [];
for (var i=0, n=datesTaken.length;i<n;i++) {
  dateArray[i]=Date.parse(datesTaken[i])
}
function isDateTaken(dateString) {
  var date = Date.parse(dateString);
  for (var i=0, n=dateArray.length;i<n;i++) {
    console.log(date+'\n'+dateArray[i]);
    if (date === dateArray[i]) return true;
  }
}


$(document).ready(function() {
  $("#emf-form").bind("submit",function(e) {
    var el = $("#element_6");
    var dateString = el.val();
    var dateParts = dateString.split(/[\-|\/|\.]/);
    var usDateString = dateParts[1]+"/"+dateParts[0]+"/"+dateParts[2];
    if (isDateTaken(usDateString)) {
      alert('Sorry, this date is not available');
      el.focus();
      e.preventDefault();
    }
  });
});
</script>

</head>

<body>




<form id="emf-form" enctype="multipart/form-data" method="post" action="." name="emf-form">
  <table style="text-align:left;" cellpadding="2" cellspacing="0" border="0" bgcolor="#FFFFFF">
    <tr>
      <td style="" colspan="2">
        <font face="Verdana" size="2" color="#000000"><b style="font-size:20px;">Enquiry</b><br />
        <label style="font-size:15px;">Please give brief details of your enquiry, We will then get back to you to discuss and answer any questions you may have.<br /></label><br /></font>
      </td>
    </tr>
    <tr valign="top">
      <td id="td_element_label_0" align="left">
        <font face="Verdana" size="2" color="#000000"><b>Your Name</b></font>
      </td>
      <td id="td_element_field_0" style="">
        <input id="element_0" name="element_0" value="" size="50" class="validate[optional]" type="text" />
        <div style="padding-bottom:8px;color:#000000;"></div>
      </td>
    </tr>
    <tr valign="top">
      <td id="td_element_label_1" align="left">
        <font face="Verdana" size="2" color="#000000"><b>Your Email Address</b></font>
      </td>
      <td id="td_element_field_1" style="">
        <input id="element_1" name="element_1" class="validate[optional,custom[email]]" value="" size="60" type="text" style="width: 311px" />
        <div style="padding-bottom:8px;color:#000000;"></div>
      </td>
    </tr>
    <tr valign="top">
      <td id="td_element_label_2" align="left">
        <font face="Verdana" size="2" color="#000000"><b>Telephone</b></font>
      </td>
      <td id="td_element_field_2" style="">
        <input id="element_2" name="element_2" value="" size="30" class="validate[optional]" type="text" />
        <div style="padding-bottom:8px;color:#000000;"></div>
      </td>
    </tr>
    <tr valign="top">
      <td id="td_element_label_6" align="left">
        <font face="Verdana" size="2" color="#000000"><b>Date of Wedding/Event<br />
        (if known/applicable)</b></font>
      </td>
      <td id="td_element_field_6" style="">
        <input id="element_6" name="element_6" value="" size="34" class="validate[optional]" type="text" style="width: 113px" />
        <div style="padding-bottom:8px;color:#000000;"></div>
      </td>
    </tr>
    <tr>
      <td colspan="2" align="left">
        <input name="element_counts" value="8" type="hidden" /> <input name="embed" value="forms" type="hidden" /><input value="Send Enquiry" type="submit" />
      </td>
    </tr>
  </table>
</form><script type="text/javascript">
//<![CDATA[
var EMF_Safari_Captcha = (function(){
        this.isChrome = (/chrome/.test(navigator.userAgent.toLowerCase()));
        this.isSafari = !this.isChrome && (/safari/.test(navigator.userAgent.toLowerCase()));
        this.process_captcha = function(){
                EMF_jQuery('a#captcha_code_refresh').trigger('click');
                get_valid_captcha();
        }
        this.firstTimeSession = true;
        this.safari_submit_session_form = function(){
                if (this.firstTimeSession) {
                                this.firstTimeSession = false;
                                EMF_jQuery("#safari_sessionform").submit();
                                setTimeout('process_captcha()',2000);
                }
        }
        return this;
})();
EMF_jQuery(function(){
        EMF_jQuery("#emf-form").validationEngine({
                validationEventTriggers:"blur",
                scroll:true
        });




        EMF_jQuery("#emf-form ul li").mousedown(highlight_field_on_mousedown);
        EMF_jQuery("#emf-form ul li input, #emf-form ul li textarea, #emf-form ul li select").focus(highlight_field_on_focus);

        var form_obj=EMF_jQuery("#emf-container form");
        if(form_obj.length>0 && form_obj.attr('action').indexOf('#')==-1){
                form_obj.attr('action', form_obj.attr('action')+document.location.hash);
        }

});

EMF_jQuery(window).load(function(){
        var parent_url = decodeURIComponent(document.location.hash.replace(/^#/, ''));
        XD.postMessage(get_frame_height(), parent_url, parent);
});

//]]>
</script>



</body>

</html>

Open in new window

0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Scripting vs. Programming languages 25 115
onOpen 14 42
Different Delete Messages 7 19
jqplot Pie Chart - javascript 2 14
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'…
Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
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 how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

758 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now