I'm trying to validate a form here and I'm almost done. The only issue is I can't figure out a way of validating the dates field to check whether the date that has been put in hasn't passed. It has to be done through Javascript... btw, here is the HTML:
<label for="reservationDate">Date of reservation (DD/MM/YYYY):</label>
<input type="text" id="date" name="date" onblur="validateDate(date)">
<span id="dateError" style="display: none;">Please enter your date of reservation in this format DD/MM/YYYY</span>
Here is the Javascript:
function validateDate(x) {
var re = /^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})$/;
if(re.test(document.getElementById(x).value)){
document.getElementById(x).style.background ='#ccffcc';
document.getElementById(x + 'Error').style.display = "none";
return true;
} else{
document.getElementById(x).style.background ='#e35152';
document.getElementById(x + 'Error').style.display = "block";
return false;
}
}
Hope someone can help :)
Here's some code to make this a specific answer to suit your needs:
function validateDate(x) {
var re = /^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})$/;
var entered = new Date(document.getElementById(x).value);
var today = new Date();
if( entered > today ) {
document.getElementById(x).style.background ='#ccffcc';
document.getElementById(x + 'Error').style.display = "none";
return true;
} else{
document.getElementById(x).style.background ='#e35152';
document.getElementById(x + 'Error').style.display = "block";
return false;
}
}
Here is the working, tested code: http://jsfiddle.net/digitalextremist/rwhhg/1/
Some past answers which are pieces but not really the whole deal:
Check if date is in the past Javascript
Validate that end date is greater than start date with jQuery
Javascript to validate date entered
Related
[I have updated this question below, please see new question on infinite looping of alert]
I have a date of birth field in my form and there is an input field as well as date picker.
After keying in the correct value, the change function is activated and runs the logic as below to do some processing to the date of birth to get age.
However, when I use alert() to prompt for the value of the date of birth, I am not able to see the value I keyed in reflected, instead, it is showing an empty string.
I tried document.getElementById("9_element14").value, but that didn't work, it showed undefined. So I switched to jQuery and now it shows empty string.
It is a Wordpress form maker form, so there is restriction in amending the HTML, but I can change the JavaScript.
Any advice is much appreciated.
The link to the form is here:
http://lionfish.vodien.com/~scforgsg/RC7/menu-parent-courses/course-application/
My codes are as below:
HTML
<tr id="9" type="type_date"><td valign="middle" align="left" id="9_label_section14" class="">
<span id="9_element_label14" class="label">Date of Birth:</span>
<span id="9_required_element14" class="required"> *</span></td>
<td valign="middle" align="left" id="9_element_section14" class=" toolbar_padding"><input type="hidden" value="type_date" name="9_type14" id="9_type14">
<input type="hidden" value="yes" name="9_required14" id="9_required14">
<input type="text" value="" class="wdform_date" id="9_element14" name="9_element14" maxlength="10" size="10" onchange="change_value('9_element14')">
<input id="9_button14" type="reset" value="..." format="%d-%m-%Y" onclick="return showCalendar('9_element14' ,'%d-%m-%Y')" class="button">
</td>
</tr>
JAVASCRIPT
// before form is load
function before_load()
{
}
$(document).ready(function() {
$('[id$=11]').hide();
$('[id$=49]').hide();
});
// before form submit
function before_submit()
{
}
// before form reset
function before_reset()
{
}
function on_choose_course() {
var course = document.getElementById("1_element14");
var selected = course.options[course.options.selectedIndex].value;
if (selected=="Canoe Polo Lvl 1" || selected=="Kayaking Orientation" || selected=="1 Star Award"){
$('[id$=49]').hide();
}
else{
$('[id$=49]').show();
}
}
$(function(){
$('[id$=9_element14]').change(function(e) {
on_date_select();
});
});
function ValidateDate(dtValue)
{
var dtRegex = new RegExp(/\b\d{1,2}[\-]\d{1,2}[\-]\d{4}\b/);
return dtRegex.test(dtValue);
}
function on_date_select() {
//calculate age
var current_year = new Date().getFullYear();
if ($('[id$=9_element14]').length) {
var dob = $('[id$=9_element14]').val();
alert($('[id$=9_element14]').val());
if (ValidateDate(dob)){
var age = current_year - substr(dob, 6, 10);
alert(substr(dob, 6, 10));
alert(age);
if (age<21){
//show declaration is 21 and above
$('[id$=11]').show();
}
if (age>=21){
//show declaration is 21 and above
$('[id$=11]').hide();
}
}//end validatedate
}//end check empty
}
==================================================================
Thanks guys for helping! Using jsfiddle and making changes here and there, I derived the conclusion that the way I was using substring for dob was not working, causing the whole function to fail.
So now I have corrected it. Only problem now is that I am getting an infinite looping of alerts when date of birth is invalid.
NEW CODES:
// before form is load
function before_load()
{
}
$(document).ready(function() {
$('[id$=11]').hide();
$('[id$=49]').hide();
});
// before form submit
function before_submit()
{
checkDetails($('[id$=15_element140]'),$('[id$=21_element14]'));
}
// before form reset
function before_reset()
{
}
function on_choose_course() {
var course = document.getElementById("1_element14");
var selected = course.options[course.options.selectedIndex].value;
if (selected=="Canoe Polo Lvl 1" || selected=="Kayaking Orientation" || selected=="1 Star Award"){
$('[id$=49]').hide();
}
else{
$('[id$=49]').show();
}
}
function checkDetails(e,f){
if (e.checked && (f.trim()).length==0){
alert("Please give details about the medical condition.");
e.focus();
}
}
$(function(){
$('[id$=9_element14]').change(function(e) {
on_date_select();
});
});
function ValidateDate(dtValue)
{
var dtRegex = new RegExp(/\b\d{1,2}[\-]\d{1,2}[\-]\d{4}\b/);
return dtRegex.test(dtValue);
}
function on_date_select() {
//calculate age
var current_year = new Date().getFullYear();
if ($('[id$=9_element14]').length) {
var dob = $('[id$=9_element14]').val();
if (ValidateDate(dob)){
var age = current_year - dob.substring(6, 10);
if (age<21){
//show declaration is 21 and above
$('[id$=11]').show();
}
if (age>=21){
//show declaration is 21 and above
$('[id$=11]').hide();
}
}else{
$('[id$=9_element14]').focus(
function() {
alert("Date of Birth is invalid");
}
);
}//end validatedate
}//end check empty
}
The ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
Change your element identificators according the rules and everything will work.
More information here and here.
I have a jsp code which on submit calls this function
function filterExcessPage() {
setDefaultValues();
var fromLast =document.getElementById('fromLast').value;
var fromDate =document.getElementById('fromDate').value;
var toDate =document.getElementById('toDate').value;
$("#excessListForm").submit(function() {
if((toDate.length>0) && (fromDate.length==0)) {
$('#validateDate').text('*from date is mandatory');
return false;
}else if ((fromDate.length>0) && (new Date(fromDate)>new Date())) {
$('#validateDate').text('*from date should be less than current date');
excessListForm.fromDate.value="";
return false;
}else if ((toDate.length>0) && (new Date(toDate)>new Date())) {
$('#validateDate').text('*to Date should be less than current date');
excessListForm.toDate.value="";
return false;
}else {
var queryUrl = "/excessManagement.web/inbox.htm?excessFilteredData=true&fromLast=" + fromLast+"&fromDate="+fromDate+"&toDate="+toDate;
excessListForm.action = queryUrl;
excessListForm.submit();
}
});
}
function setDefaultValues() {
excessListForm.cif.value="";
excessListForm.customerName.value="";
excessListForm.fromLast.value="";
excessListForm.fromDate.value="";
excessListForm.toDate.value="";
}
The fromdate and todate values reappear on form submission....
After form submission the values displayed in fromdate,todate textboxes are in the format i am using in my java class ....
I need to set the values to "" after form submission...
set in client side
var fromDate =document.getElementById('fromDate').value;
var toDate =document.getElementById('toDate').value;
fromDate.value= "";
toDate.value =""
I have a registration form with date of birth as one of the fields, I have written a function for future date which has to be invalid. But when the user puts a future date it still submits the form, although alert is being made to the user.
This is the function for alert, and its working fine.
var user_birth_year=document.getElementById("birth_year").value;
var user_birth_month=document.getElementById("birth_month").value;
var user_birth_day=document.getElementById("birth_day").value;
var userDate = new Date(user_birth_year,user_birth_month-1,user_birth_day);
var currentDate = new Date();
var res="Invalid date";
if(currentDate.getTime() < userDate.getTime() ) {
document.getElementById('registererror').innerHTML = "<span class='errorMsg'>"+res+"</span>";
document.getElementById('registererror').style.display = 'block';
} else {
document.getElementById('registererror').style.display = 'none';
}
Usually to stop the submit of a form, you need to return false on the form submit event.
I have two input fields with date1 and date2.Below this two fields i need a button that when i press it, will create a number of input fields equal to the number of months between the 2 date fields.
For example i have date1=2012-03-21 and dat2=2012-06-21. It should generate 3 input fields
Can you help me with this one?
Let's assume the HTML looks something like this:
<div id="dateRange">
<input type="text" id="startDate">
<input type="text" id="endDate">
</div>
<div id="monthlyEntries"/>
Now, a month is not a uniform number of days ("30 days has September, April, June,and November..."), so I'm guessing the day portion of the dates don't matter.
Then, the javascript to call on change (or clicking a button, or whatever), would look something like this:
function buildMonthlyEntries() {
var startDate = new Date(document.getElementById('startDate').value);
var endDate = new Date(document.getElementById('endDate').value);
if(startDate == "Invalid Date" || endDate == "Invalid Date") { return null; }
var entryCount = (endDate.getMonth() + endDate.getFullYear()*12) - (startDate.getMonth() + startDate.getFullYear()*12);
var monthlyEntries = document.getElementById('monthlyEntries');
monthlyEntries.innerHTML = "";
for(var i = 0; i < entryCount; i++) {
var textElement = document.createElement('input');
textElement.setAttribute('type', 'text');
textElement.setAttribute('id', 'entry' + i);
monthlyEntries.appendChild(textElement);
}
return null;
}
You can run a loop based upon the difference in the dates. In pseudo code it would be something like
var difference = month2 - month1;
for(x=0;x<difference,x++){
add inputfield;
}
I have a html input button like this
<input type="button" id="send_button" class="form_button" value="Send" onclick="return validateTextBoxes();" runat="server" />
And also I have javascript
<script language="javascript">
function validateTextBoxes()
{
var reading1 = document.getElementById('<%= meterReading1.ClientID%>').value;
var error = document.getElementById('<%= lblError.ClientID%>');
var btn = document.getElementById('<%= send_button.ClientID%>');
var ValidationExpression = /[\d]/;
if (reading1 == "" )
{
error.innerHTML = "Please enter Water Meter Reading.";
return false;
}
else if(!ValidationExpression.test(reading1)) {
error.innerHTML = "Please enter valid Meter Reading(It Contains only numbers)";
return false;
}
else
{
error.innerHTML = "";
return true;
}
}
</script>
And I am also calling this server click event in the code behind file
this.send_button.ServerClick += new System.EventHandler(this.send_ok);
So here is the problem when javscript returns true its not firing the serverclick event.
Please help me where I am doing wrong(I am using framework 1.1)
Thanks
I had this problem once and I actually had to do something like this:
onclick="if (validateTextBoxes()) { return true; } else { return false; }"
You absolutely should not have to do this and it made no sense to me why it would be have this way, but alas, I tried it and it worked :(