jquery Datepicker date range validation - javascript

I have a field like Born date. I have used jquery datepicker to show the calender so that user can select the date.Now I have a problem.
In the the Born date field there is a option to choose between which opens two date picker fields like
Born Date -- Between--------- ---From------- And --To----------
Now the problem is if the user selects a date in 'To field' which is less than 'From field' and press the submit button it gets submitted. I need to prevent it from submitting and display appropriate message so the user enters right date .
Please Help.
Here is the code that i am using
<input id="borndate" class="dateISO" onchange="checkDate('borndate');">
</input>
<span id="span_borndate" style="display:none">
<input id="borndate" class="dateISO" onchange="checkDate('borndate');">
</span>
This is the Java script i am using
function checkdate(fieldname) {
var comparator = '#comp_' + fieldName;
var compVal = $(comparator).val();
Value = $('#' + fieldName).val();
var fromDate = jQuery.datepicker.parseDate('mm-dd-yy', Value, null);
Values = $('#' + fieldName + '-to').val();
var toDate = jQuery.datepicker.parseDate('mm-dd-yy', Values, null);
$('#span_' + fieldName).find('.error').remove();
if (compVal == "Between") {
if (toDate < fromDate) {
$('#span_' + fieldName).append("<label class='rangeError' generated='false'>Start date should come before end date</label>");
return false;
}
}
return true;
}
And this is the function which is called again while submitting
function validateforms() {
var valid = true;
$('//classnamefor table rows which includes the date td').each(function (index) {
fieldName = $(this).attr("name");
if ($('#' + fieldName).hasClass('dateISO')) {
valid = checkDate(fieldName);
}
}
return valid;
}

Try this
http://jqueryui.com/demos/datepicker/#date-range
and make the textboxes readonly='true'
<input type="text" id="from" name="from_date" value="" readonly="true"/>
<input type="text" id="to" name="to_date" value="" readonly="true"/>

Related

Date comparison on input, client side MVC

I have a function that compares 2 dates, Start_Date and End_Date. If the start date is greater then the end date, alert a message saying "The start date exceeds End Date. Please check the date and re-enter it." Also, this should be compared right after a click away from the text box.
The below code doesn't seem to be doing justice. Any suggestions?
JS Code:
$("td[start] > input").on("change", function () {
alert("here first");
var cur_td = $(this).closest("tr");
var startdate = $(this).val();
var enddate = cur_td.find("td[end]").text();
var d1 = Date.parse(startdate);
var d2 = Date.parse(enddate);
checkdates(d1, d2);
});
function checkdates(s_date, e_date) {
if (s_date > e_date) {
alert("The date " + s_date + " exceeds End Date. Please check the date and re-enter it.");
}
}
Razor View:
<td start><input class="start" id=#item.ID type="text" actual="1" value='#(item.Start_Date == null ? "" : Convert.ToDateTime(item.Start_Date).ToString("MM-dd-yyyy"))' readonly="readonly" /></td>
<td end><input class="end" id=#item.ID type="text" actual="1" value='#(item.End_Date == null ? "" : Convert.ToDateTime(item.End_Date).ToString("MM-dd-yyyy"))' readonly="readonly" /></td>
You try 'keyup' instead of 'change.
$("td[start] > input").on("keyup", function () { })
or
if you want to use on('change'), then you must use input type date or any date-picker.like
<input class="start" id=#item.ID type="date" actual="1" value='#(item.Start_Date == null ? "" : Convert.ToDateTime(item.Start_Date).ToString("MM-dd-yyyy"))' readonly="readonly" />

Converting HTML form input into Javascript variables and comparing values

I am trying to compare the birth dates of two people. Person 1 and Person 2 input their names and dates of birth in an HTML form, and I want to use Javascript to compare the two dates and print out which person is older on the HTML page. However, I'm not sure how to submit the form and compare the dates. Here is what I have so far for the HTML:
<form id="form1">
Full name of first person: <input type="text" name="name1"><br>
Birthday: <input type="date" date="date1"><br>
<br>
Full name of second person: <input type="text" name="name2"><br>
Birthday: <input type="date" date="date2"><br>
</form>
And the Javascript:
var name1 = document.getElementsByName("name1");
var name2 = document.getElementsByName("name2");
var date1 = document.getElementsByName("date1");
var date2 = document.getElementsByName("date2");
How do I submit the variables in HTML and then have Javascript compare the two dates?
You forgot two things:
A submit button.
A submit handler.
I guess this solves your question.
window.onload = function () {
document.getElementById("form1").onsubmit = function () {
var name1 = document.getElementById("name1");
var name2 = document.getElementById("name2");
var date1 = document.getElementById("date1");
var date2 = document.getElementById("date2");
if ((new Date(date1.value)).getTime() < (new Date(date2.value)).getTime()){
console.log(name1.value + " is greater than " + name2.value)}
else if ((new Date(date1.value)).getTime() > (new Date(date2.value)).getTime()){
console.log(name2.value + " is greater than " + name1.value)}
else{
console.log(name2.value + " and " + name1.value + " are of same age.")};
};
};
<form id="form1">
Full name of first person: <input type="text" id="name1"><br>
Birthday: <input type="date" id="date1"><br>
<br>
Full name of second person: <input type="text" id="name2"><br>
Birthday: <input type="date" id="date2"><br>
<input type="submit" value="Check" />
</form>
You need to add an action to the form and a submit button. Then you can add an onsubmit call from your button to invoke a simple string comparison function to see which number is greater
Basic form data access demo
var compare = function () {
var form = document.getElementById("form1");
var output = document.getElementById("demo");
output.innerHTML = "";
for(var i = 0; i< form.length; i++){
output.innerHTML = output.innerHTML +" "+ form.elements[i].value;
};
};
<form id="form1">
Full name of first person: <input type="text" id="name1"><br>
Birthday: <input type="date" id="date1"><br>
<br>
Full name of second person: <input type="text" id="name2"><br>
Birthday: <input type="date" id="date2"><br>
</form>
<input type="button" name="submit" value="Compare " onclick="compare()" />
<p id="demo"></p>
Well, let's go step by step on this
1. How to submit a form
In HTML you have 2 ways of submitting a form:
Through an <input> tag with the type="submit" attribute (resulting in <input type="submit" />
Trough a <button> tag with the type="submit" attribute (resulting in <button type="submit">...content...</button>
Now when these buttons get clicked, they will trigger the <form>'s submit event.
2. How to subscribe to a form's submit event
As when submitting a form, there're (without any external libraries) 2 ways of subscribing to a form's submit event:
Directly setting a property on the form: formvar.onsubmit = function() { /* ... do stuff ... */ } (not really recommended as other plugins/scripts might overwrite this)
Adding an event listener: formvar.addEventListener("submit", function() { /* ... do stuff ... */ } (better than directly setting a property as this won't be removed when another script subscribes to the same event)
3. Comparing dates
Well, first you'd have to transform the dates from the string value you got from the textbox to a proper Date type:
date1 = Date.parse(date1.value);
date2 = Date.parse(date2.value);
And then with a simple arithmetic operator you can find out which one of them is the oldest:
var difference = date2 - date1;
if(difference > 0)
{
// Second person is the oldest
}
else if (difference < 0)
{
// First person is the oldest
}
else
{
// They are the same age
}
You don't need to submit the form to check the difference. A simple onclick function or click event listener will do.
You need to check if they are older, younger, or the same age. Try it below. You code wasn't working because you didn't have a name property for your dates. I switched them to use ids.
document.getElementById("theButton").addEventListener('click', checkOldest);
function checkOldest() {
var name1Value = document.getElementById("name1").value,
name2Value = document.getElementById("name2").value,
date1Value = document.getElementById("date1").value,
date2Value = document.getElementById("date2").value,
result = document.getElementById("result");
// make sure you have input for both birthdates and names
if (name1Value && name2Value && date1Value && date2Value) {
var dateOneComparedToTwo = new Date(date1Value) - new Date(date2Value);
if (dateOneComparedToTwo < 0) {
result.innerText = name1Value + ' is older than ' + name2Value + '!';
} else if (dateOneComparedToTwo > 0) {
result.innerText = name1Value + ' is younger than ' + name2Value + '!';
} else {
result.innerText = name1Value + ' and ' + name2Value + ' are the same age!';
}
} else {
result.innerText = "You need to fill out the form completely!";
}
}
<form id="form1">
Full name of first person: <input type="text" id="name1" name="name1"><br>
Birthday: <input type="date" id="date1" name="date1"><br>
<br>
Full name of second person: <input type="text" id="name2" name="name2"><br>
Birthday: <input type="date" id="date2" name="date2"><br>
<button id="theButton">Who's oldest?</button>
</form>
<p id="result">
Fill out the form please!
</p>

Jquery validation - field focus

I have a form with list of input fields to be filled in.The values entered will be validated against the min and max criteria.If the entered value doesn't fall into the criteria , users need to be triggered to enter the reason followed by entering the after weight.
<c:forEach var="Item" items="${listBean.nameList}" varStatus="status">
<input type="number" class="required" name="nameList<c:out value='[${status.index}]'/>.initialWeight" onchange="checkOnChange(this,'<c:out value="${Item.personId}"/>','<c:out value="${Item.minWeight}"/>','<c:out value="${Item.maxWeight}"/>')">
<input type="number" class="required" name="nameList<c:out value='[${status.index}]'/>.finalWeight" onchange="checkOnChange(this,'<c:out value="${Item.personId}"/>','<c:out value="${Item.minWeight}"/>','<c:out value="${Item.maxWeight}"/>')">
<input type="text" class="formtext" name="nameList<c:out value='[${status.index}]'/>.Reason" value="" maxlength="255" size="25">
</c:forEach>
So once the initalWeight is entered , onchange event will be triggered to check whether the value is with in the min and max value.If it doesn't fall in to the criteria ,users will be alerted to enter reason and the screen focus should be on the reason field.
function checkOnChange(name, id, min, max)
{
var check = true;
var originalValue = '';
var minimum = eval(min);
var maximum = eval(max);
var nameVal = eval(name.value);
if (nameVal > maxVal)
{
alert(id + ' Enter the reason before proceeding');
return false;
}
if (itemVal < minVal)
{
alert(id + ' Enter the reason before proceeding');
return false;
}
}
JSFiddle link : http://jsfiddle.net/jegadeesb/ehehjxbp/
Is there a better way to achieve this .Kindly share your suggestions.
Thanks for your valuable suggestions and time
Add the reason field an ID and the set focus on it using the focus method
<c:forEach var="Item" items="${listBean.nameList}" varStatus="status">
<input type="number" class="required" name="nameList<c:out value='[${status.index}]'/>.initialWeight" onchange="checkOnChange(this,'<c:out value="${Item.personId}"/>','<c:out value="${Item.minWeight}"/>','<c:out value="${Item.maxWeight}"/>')">
<input type="number" class="required" name="nameList<c:out value='[${status.index}]'/>.finalWeight" onchange="checkOnChange(this,'<c:out value="${Item.personId}"/>','<c:out value="${Item.minWeight}"/>','<c:out value="${Item.maxWeight}"/>')">
<input type="text" class="formtext" name="nameList<c:out value='[${status.index}]'/>.Reason" id="reason" value="" maxlength="255" size="25">
</c:forEach>
function checkOnChange(name, id, min, max)
{
var check = true;
var originalValue = '';
var minimum = eval(min);
var maximum = eval(max);
var nameVal = eval(name.value);
if (nameVal > maxVal)
{
alert(id + ' Enter the reason before proceeding');
document.getElementById("reason").focus();
return false;
}
if (itemVal < minVal)
{
alert(id + ' Enter the reason before proceeding');
document.getElementById("reason").focus();
return false;
}
}

comparing dates using script in forms

I am trying to validate date based on date entered in first textbox. If second textbox exceeds one year from the date entered in first textbox, then it should display an alert and blank the second date field textbox. Both the textboxes are readonly and gets the values from calender. I tried the below code but the alert is popping up even if the year is not more than a year. Also ,is it possible to pass 'name3' and 'name4' IDs as parameters. I need to apply this code to 10 rows.
<script>
function fixup()
{
var parts = document.getElementById('name3').value.split("-");
parts[2] = Number(parts[2]) + 1;
var pj = parts.join("-");
var x=document.getElementById('name4').value;
if(x>pj)
{
alert("Expiration date should not be greater than one year from start date");
document.getElementById('name4').value = "";
return false;
}
return true;
}
</script>
</head>
<body>
<form onsubmit="return fixup()">
<table>
<tr>
<td><input type="text" name="soname3" id="name3" size="15" readonly="readonly">
<img src="../Image/cal.gif" id="" style="cursor: pointer;" onclick="javascript:NewCssCal('name3','MMddyyyy','dropdown',false,'12')" /></td>
<td><input type="text" name="soname4" id="name4" size="15" readonly="readonly">
<img src="../Image/cal.gif" id="" style="cursor: pointer;" onclick="javascript:NewCssCal('name4','MMddyyyy','dropdown',false,'12'); " /> </td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
I did Below code after suggestions by dm03514. but validation is not working..
function test()
{
start = document.getElementById('name3').value;
end = document.getElementById('name4').value;
compare(start, end);
}
function compare(sDate, eDate)
{
function parseDate(input) {
var parts = input.match(/(\d+)/g);
return new Date(parts[2], parts[0]-1, parts[1]); //parts[2] is year, parts[0] is month and parts[1] is date.
}
var parse_sDate = parseDate(sDate);
var parse_eDate = parseDate(eDate);
parse_sDate.setDate(parse_sDate.setFullYear(parse_sDate.getMonth() + 12));
if(parse_sDate>parse_eDate)
{
alert("End date should not be greater than one year from start date");
}
}
I would strongly recommend using a library like moment.js for handling dates. It has extensive date formatting and parsing features as well as comparison helpers:
var d1 = moment(document.getElementById('name3').value, 'YYYY-MM-DD');
var d2 = moment(document.getElementById('name4').value, 'YYYY-MM-DD');
var diff = d2.diff(d1, 'years');
if (diff > 0) {
alert("Expiration date should not be greater than one year from start date");
}
See also:Compare two dates in JS

How can I validate multiple different form fields, I have searched and searched for a week

How do I validate dd/mm/yyyy, numeric loan amount, alphabetic first, last name together. I am having trouble using this forum. Thanks for responding so fast!
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
<!--//
function validate(form){
var message = 'Please fill in the following fields:\n\n\t';
for(var i=0; i<form.elements.length; i++){
if(form.elements[i].value.length == 0){
message+= form.elements[i].name.toUpperCase()+'\n\t';
}
}
message+= '\nOK submit incomplete form';
message+= '\nCANCEL return to the form';
message = confirm(message);
if(!message){ return false };
else{ return true };
}
//-->
</script>
</head>
<body>
<form name="loanform" action="processform.htm" method="get" onsubmit="return validate(this)">
First Name: <input type="text" name="firstname" maxlength="15"><br>
Last Name: <input type="text" name="lastname" maxlength="15"><br>
Birth Date: <input type="text" name="birthdate" maxlength="8"><br>
Loan Amount: <input type="text" name="loanamount" maxlength="6" ><br>
Years: <input type="text" name="years" maxlength="2"><br>
<br>
<input type="reset" value="clear">
<input type="submit" value="submit">
</form>
</body>
</html>
You can use a function like this. It sets up a regular expression for each type of field and then makes a table that says which regular expression to use for which form element. It uses the named form elements to access the individual values.
function validate(form) {
var nameRE = /^[A-Za-z \.]+$/;
var dateRE = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var amountRE = /^\$?[\d\.,]+$/;
var yearsRE = /^\d+$/;
var formItems = [
{name: "firstname", re: nameRE, tag: "First Name"},
{name: "lastname", re: nameRE, tag: "Last Name"},
{name: "birthdate", re: dateRE, tag: "Birth Date", isDate: true},
{name: "loanamount", re: amountRE, tag: "Loan Amount", min: 50000, max: 750000},
{name: "years", re: yearsRE, tag: "Years", min: 5, max: 30}
];
var item, val, num, month, day, year, valid, matches, incomplete = false;
var msg = 'Please fill in the following fields:\n\n\t';
for (var i = 0; i < formItems.length; i++) {
item = formItems[i];
// strip leading or trailing whitespace
var val = form[item.name].value.replace(/^\s+|\s+$/g, "");
form[item.name].value = val;
// see if it matches the regex
valid = item.re.test(val);
if (valid && item.isDate) {
matches = val.match(item.re);
month = parseInt(matches[1], 10);
day = parseInt(matches[2], 10);
year = parseInt(matches[3], 10);
if (month <= 0 || month > 12 ||
day <= 0 || day >= 31 ||
year < 1900 || year > 2020) {
valid = false;
}
}
if (!valid) {
incomplete = true;
msg += item.tag + '\n\t';
} else {
if (item.min && item.max) {
// clear out non-numeric chars
val = val.replace(/[,\$\s]/g, "");
// convert to a number
num = parseInt(val, 10);
// compare to min and max
if (num < item.min || num > item.max) {
incomplete = true;
msg += item.tag + " (must be between " + item.min + " and " + item.max + ")\n\t";
}
}
}
}
if (incomplete) {
msg += '\nOK submit incomplete form';
msg += '\nCANCEL return to the form';
return(confirm(msg));
}
return(true);
}
​
Working demo here: http://jsfiddle.net/jfriend00/GChEP/
A way to do would be to use classes to know what kind of validation you need for a given input. Also, you can use the title attribute to have a more human-friendly representiation of the input.
Your HTML would then look like:
<form name="loanform" action="processform.htm" method="get" onsubmit="return validate(this)">
First Name (text only): <input class="validate-text" title="First Name" type="text" name="firstname" maxlength="15"><br>
Last Name (text only): <input class="validate-text" title="Last Name" type="text" name="lastname" maxlength="15"><br>
Birth Date (format dd/mm/yyyy): <input class="validate-date" title="Birth Date" type="text" name="birthdate" maxlength="8"><br>
Loan Amount (US dollars, numeric only): <input class="validate-number" title="Loan Amount" type="text" name="loanamount" maxlength="6" ><br>
Years (numeric only): <input class="validate-number" title="Years" type="text" name="years" maxlength="2"><br>
<br>
<input type="reset" value="clear">
<input type="submit" value="submit">
</form>
And your JavaScript function (regular expressions seem to be the best way to go):
function validate(f) {
var message=new Array(); //will contain the fields that are misfilled
var reText=new RegExp("^[a-z \-'\.]+$", "i"); //a RegExp to match names: only letters, "-", "'" and "." allowed
var reDate=new RegExp("^[0-9]{2}/[0-9]{2}/[0-9]{4}$"); //a RegExp to match a date in the format dd/mm/yyyy
var reNumber=new RegExp("^[0-9]+$"); //a RegExp to match a number
for(var e in f.elements) { //loop on every input of the form
var test=null; //set or reset the RegExp to use for the current input
var input=f.elements[e]; //assign the input to a var (easier to type, not needed)
if(!input.className) //if this input doesn't have any class declared
continue; //then we skip the rest of the loop to keep going with the next input
var classes=input.className.split(" "); //maybe the input has several classes, so we split them in a "classes" array
for(var c in classes) { //we loop on every class of the current input
switch(classes[c]) { //and we test if the current class of the current input is one of the classes we're interested in
case "validate-text": //if it is a text
test=reText; //the variable "test" will contain the RegExp we want to use
break;
case "validate-date": //same for a date
test=reDate;
break;
case "validate-number": //and same for a number
test=reNumber;
break;
default: //if the class is not something we want, nothing to do
break;
} //end switch
} //end classes loop
//here test is either null (no "validate-something" class found for the current input), or it contains the RegExp telling us the kind of input we must validate.
if(test!=null && !input.value.match(test)) { //if it is not null and if the input's value does not match the RegExp
message.push(input.title); //we add the field to the "message" array
}
} //end input loop
if(message.length>0) { //if the arary is not empty, we display a confirm box
return confirm("Please correctly fill the following field(s), or click OK to send an incomplete form:\n"+message.join("\n"));
}
//otherwise, the form is correctly filled, we return true to submit the form
return true;
}

Categories