<tr>
<td><label>Birthdate</label>
<input type="text" placeholder="mm/dd/yyyy" name="birthdate" maxlength="10"/>
</td>
</tr>
Well, my code is working but I want my "input type text" to auto format like a date (html 5 input type=date) because in my Servlet I convert it to Age.
The problem is that, if I use the "input type=date" the conversion is error so I decided to use "input type=text" and it's working. So is it possible to auto put "/" in this format "mm/dd/yyyy"? For example, if the user input 2 character an "/" will auto input etc.
Servlet for birthdate to Age
String birthdate = request.getParameter("birthdate");
int monthDOB = Integer.parseInt(birthdate.substring(0, 2));
int dayDOB = Integer.parseInt(birthdate.substring(3, 5));
int yearDOB = Integer.parseInt(birthdate.substring(6, 10));
DateFormat dateFormat = new SimpleDateFormat("MM");
java.util.Date date = new java.util.Date();
int thisMonth = Integer.parseInt(dateFormat.format(date));
dateFormat = new SimpleDateFormat("dd");
date = new java.util.Date();
int thisDay = Integer.parseInt(dateFormat.format(date));
dateFormat = new SimpleDateFormat("YYYY");
date = new java.util.Date();
int thisYear = Integer.parseInt(dateFormat.format(date));
int calAge = thisYear - yearDOB;
if (thisMonth < monthDOB) {
calAge = calAge - 1;
}
if (thisMonth == monthDOB && thisDay < dayDOB) {
calAge = calAge - 1;
}
String age = Integer.toString(calAge);
Update in the form
<tr>
<td><label for="inputName">Birthdate</label>
<input type="text" placeholder="mm/dd/yyyy" id="input_date" name="birthdate" maxlength="10" />
</td>
</tr>
Update in the source
<script src="../scripts/formatter.js"></script>
<script src="../scripts/formatter.min.js"></script>
<script src="../scripts/jquery.formatter.js"></script>
<script src="../scripts/jquery.formatter.min.js"></script>
Added Script
<script>
$('#input_date').formatter({
'pattern': '{{99}}/{{99}}/{{9999}}',
'persistent': true
});
</script>
I also tried the javascript but it's not working...
I've been watching a project on GitHub (and providing feedback to improve it) for just such kind of formatting called formatter.js http://firstopinion.github.io/formatter.js/demos.html This might be just the thing you're looking for.
This wouldn't stop you from typing in dates like the 53rd of May... but it will help you format.
new Formatter(document.getElementById('date-input'), {
'pattern': '{{99}}/{{99}}/{{9999}}',
'persistent': true
});
or
$('#date-input').formatter({
'pattern': '{{99}}/{{99}}/{{9999}}',
'persistent': true
});
I have an alternative that works with a jquery-ui datepicker, without formatter.js. It is intended to be called from the keyup and change events. It adds zero padding. It works with various supported date formats by constructing expressions from the dateFormat string. I can't think of a way to do it with fewer than three replaces.
// Example: mm/dd/yy or yy-mm-dd
var format = $(".ui-datepicker").datepicker("option", "dateFormat");
var match = new RegExp(format
.replace(/(\w+)\W(\w+)\W(\w+)/, "^\\s*($1)\\W*($2)?\\W*($3)?([0-9]*).*")
.replace(/mm|dd/g, "\\d{2}")
.replace(/yy/g, "\\d{4}"));
var replace = "$1/$2/$3$4"
.replace(/\//g, format.match(/\W/));
function doFormat(target)
{
target.value = target.value
.replace(/(^|\W)(?=\d\W)/g, "$10") // padding
.replace(match, replace) // fields
.replace(/(\W)+/g, "$1"); // remove repeats
}
https://jsfiddle.net/4msunL6k/
use datepicker api from jquery
here is the link Datepicker
and here is the working code
<tr>
<td><label>Birthdate</label>
<input type="text" placeholder="mm/dd/yyyy" name="birthdate" id="birthdate" maxlength="10"/>
</td>
</tr>
<script>
$(function() {
$( "#birthdate" ).datepicker();
});
</script>
EDIT
$("input[name='birthdate']:first").keyup(function(e){
var key=String.fromCharCode(e.keyCode);
if(!(key>=0&&key<=9))$(this).val($(this).val().substr(0,$(this).val().length-1));
var value=$(this).val();
if(value.length==2||value.length==5)$(this).val($(this).val()+'/');
});
this is the code that you may need
here is the fiddled code
user2897690 had the right idea but it didn't accept Numpad numbers. So took their javascript and modified it to work.
Here is my interpretation of their code with the added feature.
$("input[name='birthdate']:first").keyup(function(e){
var chars = [48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105];
var key=chars.indexOf(e.keyCode);
console.log(key);
if(key==-1)$(this).val($(this).val().substr(0,$(this).val().length-1));
var value=$(this).val();
if(value.length==2||value.length==5)$(this).val($(this).val()+'/');
});
Related
I am setting the min of checkOut as the value of checkIn. My problem comes that i need to add one day to firstdate. (Should not be able to check out on or before the check in day.)
<script>
function updatedate() {
var firstdate = document.getElementById("checkIn").value;
document.getElementById("checkOut").value = "";
document.getElementById("checkOut").setAttribute("min",firstdate);
}
</script>
Check In
<input type="date" id="checkIn" onchange="updatedate();" name="checkin">
Check out
<input type="date" id="checkOut" min="" name="checkout">
It's sort of do-able but it only works in Chrome since that's the only browser that supports a date input at the moment. Oh, and this solution uses momentjs because parsing a date and correctly adding 1 day to it is way harder that it sounds.
function updatedate() {
var checkin = document.getElementById("checkIn").value;
checkin = moment(checkin);
var checkout = checkin.add(1, 'd');
document.getElementById("checkOut").setAttribute("min", checkout.format('YYYY-MM-DD'));
}
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet"/>
<div class="container">
Check In
<input type="date" id="checkIn" onchange="updatedate();" name="checkin">Check out
<input type="date" id="checkOut" min="" name="checkout">
</div>
A momentless solution is to parse the checkinDate into a JS date and and then create a new date whilst adding one day to the checkinDate. Though yeah, momentJS is the goto library when dealing with dates.
JSfiddle here:
https://jsfiddle.net/xugajae5/
There was a bit of a hack in getting the min format that the input expected:
var checkoutDateFormat = checkoutDate.toISOString().split('T')[0];
Not all browsers in use support input type date, so you'll need to deal with that to start with.
Then, you can convert the value of firstdate to a Date object, add a day, then get back a date in the required format. Your issue however is that the value of the date input (which is an ISO 8601 format date string) is treated as local, but the Date constructor will treat it as UTC.
So you need to parse the string as a local date, then add the day, then get back a string in the right format. The code below is just an example, you may wish to use a library for the date manipulation. Just remember not to parse the date string with the Date constructor.
function getTomorrow(el) {
var form = el.form;
var start = parseISOAsLocal(form.start.value);
// Check if input date was valid
if (!start.getTime()) {
form.tomorrow.value = '';
form.start.value = 'Invalid date';
return;
}
start.setDate(start.getDate() + 1);
form.tomorrow.value = formatISODate(start);
}
function parseISOAsLocal(s) {
var b = s.split(/\D/);
var d = new Date(b[0], --b[1], b[2]);
return d && d.getMonth() == b[1]? d : new Date(NaN);
}
function formatISODate(date) {
return ('000' + date.getFullYear()).slice(-4) + '-' +
('0' + (date.getMonth() + 1)).slice(-2) + '-' +
('0' + date.getDate()).slice(-2);
}
<form>
Start (yyyy-mm-dd):
<input type="date" name="start" value="2016-08-31"><br>
Tomorrow: <input type="date" name="tomorrow" readonly><br>
<input type="button" onclick="getTomorrow(this)"
value="Show tomorrow">
</form>
<script>
function updatedate(){
var checkInValue = document.getElementById("checkIn").value;
var checkInDate = Date.parse(checkInValue);
var minDate = new Date(checkInDate + 24 * 3600 * 1000);
document.getElementById("checkOut").setAttribute("min", minDate.toDateString());
}
</script>
In My Angular UI I want to disable a submit button if
1) All the inputs are null or empty
2) If the endDate field is less than the startDate itself
What I did is ...
<input type="submit" class="btn btn-default pull-right" style="width:100px;" value="Submit"
ng-disabled="groupMembershipUserInputForm.$invalid || !(!!groupmembership.chapterCode || !!groupmembership.groupCode ||
!!groupmembership.groupName || !!groupmembership.createdBy ||
!!groupmembership.createdDate || !!groupmembership.startDate ||
!!groupmembership.endDate || !!groupmembership.losCode
|| groupmembership.compareAgainstStartDate(groupmembership.endDate) )" />
All the strings empty/null checks are working fine except the date compare check .
In my controller the method looks like
$scope.groupmembership.compareAgainstStartDate = function (item) {
var startDate = $filter('date')(new Date($scope.groupmembership.startDate), 'MM/dd/yyyy');
var endDate = $filter('date')(new Date($scope.groupmembership.endDate), 'MM/dd/yyyy');
if (endDate < startDate) {
$scope.groupmembership.toggleInvalidInput = true;
}
else
$scope.groupmembership.toggleInvalidInput = false;
return $scope.groupmembership.toggleInvalidInput;
};
It is being hit , but I don't know why the disabling not happening if the date compare fails .
Please help me .
So first :
All the inputs are null or empty
For this just add a required to all your input/select/...
If you do so groupMembershipUserInputForm.$invalid will be true if one of the required fields is not filled.
This will simplify greatly you ng-disabled to the following :
ng-disabled="groupMembershipUserInputForm.$invalid ||
groupmembership.compareAgainstStartDate(groupmembership.endDate)"
This is a first valid working step. Now if you want to go further you could create a directive and have something like :
<input ng-model="afterDate" date-greater-than="beforeDate"/>
This will be usefull if you have other forms than need this. If you're interested to do this i suggest you to google something like "angular js custom validation form directive" and if you have trouble with that directive, after trying on your own, come back to us into another question.
FInally if you master custom validation form you could use angular-message. it's a little addon specifically designed to display error from forms.
Here is a sample code from https://scotch.io/tutorials/angularjs-form-validation-with-ngmessages :
<form name="myForm">
<input
type="text"
name="username"
ng-model="user.username"
ng-minlength="3"
ng-maxlength="8"
required>
<div ng-messages="userForm.name.$error">
<p ng-message="minlength">Your name is too short.</p>
<p ng-message="maxlength">Your name is too long.</p>
<p ng-message="required">Your name is required.</p>
<p ng-message="myCustomErrorField">Your name is <your custom reason></p>
</div>
<input type="submit" ng-disabled="myForm.$invalid"/>
</form>
Your logic pretty much right, I have doubt on your $scope.groupmembership.startDate and $scope.groupmembership.endDate because if I provide correct dates, then it is working as expected. Can you please try by providing some constant date to verify whether your function is behaving properly or not. For me it is working fine with actual date values.
$scope.startDate = $filter('date')(new Date("07/02/2016"), 'MM/dd/yyyy');
$scope.endDate = $filter('date')(new Date("0710/2016"), 'MM/dd/yyyy');
In your example dates are string type so you may not get correct result. To compare date first convert it to time using getTime() that will give you exact result. No need to use filter for date check.
just use like:
$scope.groupmembership.compareAgainstStartDate = function () {
var startDate = new Date($scope.groupmembership.startDate);
var endDate = new Date($scope.groupmembership.endDate);
if (endDate.getTime() < startDate.getTime()) {
$scope.groupmembership.toggleInvalidInput = true;
}
else
$scope.groupmembership.toggleInvalidInput = false;
return $scope.groupmembership.toggleInvalidInput;
};
Just convert startdate and enddate to milliseconds, and compare them.
Try the below code once:
$scope.groupmembership.compareAgainstStartDate = function () {
var startDate = new Date($scope.groupmembership.startDate).getTime();
var endDate = new Date($scope.groupmembership.endDate).getTime();
if (endDate < startDate) {
$scope.groupmembership.toggleInvalidInput = true;
} else {
$scope.groupmembership.toggleInvalidInput = false;
}
return $scope.groupmembership.toggleInvalidInput;
};
I have a form element of date type:
<input type="date" class="form-control" name="InputDOB" id="DOB"
placeholder="DOB" onblur="dateValidate()" required>
The JavaScript code is here:
function dateValidate(){
var date=new Date();
var pass1 = document.getElementById("DOB");
alert(pass1.value);
var date = new Date();
today=date.getFullYear()+'-'+(date.getMonth() + 1)+'-'+date.getDate();
if(pass1.value<today){
alert("date is correct ");
}
}
You don't need today, just change your if to
if(new Date(pass1.value)< date){
alert("date is correct ");
}
//OR
if(new Date(pass1.value)< new Date()){
alert("date is correct ");
}
Based on the code that you've posted, this is how you do it :
html:
<input type="date" class="form-control" name="InputDOB" id="DOB" placeholder="DOB" required>
application.js file that you should load into your HTML file and I'm also using JQuery to accomplish this so you should load it too.
$(document).ready(function () {
$("#DOB").on("blur", function () {
var date=new Date();
var pass1 = document.getElementById("DOB");
alert(pass1.value);
today=date.getFullYear()+'-'+(date.getMonth() + 1)+'-'+date.getDate();
alert(today);
if(pass1.value<today){
alert("date is correct ");
}
})
});
DEMO:
http://fiddle.jshell.net/a2fjzqzw/
I always use moment.js with JavaScript when messing with dates. It mitigates most if not all the hardship when manipulating dates in JavaScript and is a brilliant library.
http://momentjs.com/docs/#/displaying/difference/
The difference method may get you where you need, if not I'm sure you can find a solution in the API.
you need to use getTime(); to compare two dates like
function dateValidate(){
var input = document.getElementById("DOB");
alert(input.value);
var inputDate = new Date(input.value).getTime();
var today = new Date().getTime();
if(inputDate<today){
alert("date is correct");
}
}
Demo
I have 3 input fields all together.
Contract period: 1 years(for example)
start date : 30 - 1- 2012 (for example)
end date : ????
(Can we get the end date automatically according to the contract period mentioned, which mean if the date after 1 year is 30-1-2013 can we get it automatically in the third field after mentioning the first and second field).
Possible, using onSelect option of jQuery datepicker.
1) get the value of contract year and parse it as integer.
var addYears = parseInt($('#contract').val(), 10);
2) Split the selected date in startDate, as below
var t = date.split('/');
3) Now add the years and parse it as Date object.
var fin = new Date(parseInt(t[2], 10) + addYears, --t[0], t[1]);
Finally,
HTML:
In years only:
<input id="contract" type="text" />
<input id="start" type="text" />
<input id="end" type="text" />
JS:
$('#end').datepicker();
$('#start').datepicker({
onSelect: function (date, args) {
var addYears = parseInt($('#contract').val());
var t = date.split('/');
var fin = new Date(parseInt(t[2], 10) + addYears, --t[0], t[1]);
$('#end').datepicker("setDate", fin);
}
});
JSFiddle
I am new to Javascript programming and I am trying to validate a date entered into an <input> from a calender snippet which is obtained from an external Javascript file. I am trying to validate the date to check if the user entered a past date. If the entered date is a past date, then I need to print a warning message to enter a valid date in future period.
I accept input date field in following HTML code:
<input size="12" id="inputField" name="inputField" autofocus="" type="date" oninput="return dateValidate(inputField)"/>
My Javascript function to validate input date is:
<script type="text/javascript">
function dateValidate(inputField)
{
var v2 = document.getElementById('inputField');
var pickeddate = new Date(v2.Value);
todayDate = new Date();
if(pickeddate > todayDate){
return true;
} else {
alert("Enter a valid Date");
}
}
But this code doesn't seem to be working. I want this Javascript function to be run when I enter a past date in the <input> field and tab out. I want to validate date when it is entered in the field, not when the form is submitted.
It is not working since there is a issue in your code, just replace this:
var pickeddate = new Date(v2.Value);
with this:
var pickeddate = new Date(v2.value); // 'value' should be in lower case
Since, it was not correct, the pickeddate was always undefined and code didn't worked.
You may try this
HTML
<input size="12" id="inputField" name="inputField" autofocus="" type="date" onblur="return dateValidate(this)"/>
JS
function dateValidate(inputField)
{
var pickeddate = new Date(inputField.value);
var todayDate = new Date();
if( pickeddate > todayDate )
{
return true;
}
else
{
alert("Enter a valid Date");
}
}
DEMO.