How to restrict user to enter date manually in date field - javascript

I am working on an application in which i want to restrict user to manually enter the date in the type=date field in html page.
I want to restrict the user to select the date only from the calender display which is MM/DD/YYYY.
Below is the code in html page :
<input type="date" name="bankTrans" ng-model="orderAstro.paymentDate"
class="form-control" id="bankTrans"
ng-disabled="isDisabled" required />
Also attaching the image for error clarity :
Image for error clarity

use following line of code to restrict manual date field entry using jquery.
$("input[type='date']").keydown(function (event) { event.preventDefault(); });

Edit 1:
Your question makes sense.
The best way to work with a date is to disable manual entry and allow changes only using the Date Picker.
Add a 'readonly' attribute to the input field:
<input type="date" readonly name="bankTrans"
ng-model="orderAstro.paymentDate" class="form-control"
id="bankTrans" ng-disabled="isDisabled" required />
Do you want the code for above Angular js file and HTML as well or this much is fine.

Edit 2:
Disabling the manual Entry of Date and allowing only through Date Picker.
HTML code:
<input type="text" readonly class="form-control" datepicker-popup="{{clCtrl.format}}"
ng-model="clCtrl.QualityExpirationDate" is-open="clCtrl.openedQualityDate"
min-date="clCtrl.minDate" datepicker-options="clCtrl.dateOptions"
ng-required="true" close-on-date-selection="true"
show-button-bar="false" />
js file:
$scope.$watch('dt', function(val) {
$scope.isValidDate = isNaN(new Date(val).getTime());
});
self.dateOptions = {
formatYear: 'yy',
startingDay: 1
};
self.formats = ['MM-dd-yyyy', 'MM/dd/yyyy', 'MM.dd.yyyy', 'shortDate'];
self.format = self.formats[0];
self.openQualityDate = function ($event) {
$event.preventDefault();
$event.stopPropagation();
self.openedQualityDate = true;
};
self.toggleMin = function () {
self.minDate = self.minDate ? null : new Date();
};
self.toggleMin();
self.clear = function () {
self.QualityExpirationDate = null;
};

Please ignore this, is not solving the issue, as intended.
This might help: https://jsdaddy.github.io/ngx-mask-page/main#prefix
<input mask="00/00/0000">

what worked for me!
added the following attributes to my date type input tags.
<input type="date" name="dob" "minlength": "10", "maxlength": "10", class="form-control" />

Related

Bootstrap Datepicker With Daterange Not Saving Value as the Specified Format

I have a booking form that requires two dates, so I'm using the built in option that Bootstrap datepicker has (it consists on calling the datepicker function on the father element that contains the inputs), to show the daterange selected, this is my HTML:
<div class="grupo vip-fechas input-daterange">
<div class="barra verde"> <span>¿Cuándo llegas?</span></div>
<input type="text" class="input calendario" id="entrada_input" name="entrada_input" placeholder="Selecciona una fecha">
<input type="hidden" id="fecha_inicio" name="fecha_inicio">
<div class="barra verde"> <span>¿Cuándo te vas?</span></div>
<input type="text" class="input calendario" id="salida_input" name="salida_input" placeholder="Selecciona una fecha">
<input type="hidden" id="fecha_fin" name="fecha_fin">
</div>
This is my Javascript code:
$(document).ready(function(){
iniciarFechas();
});
function iniciarFechas(){
var date = new Date();
var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
var date_hidden;
$('.vip-fechas.input-daterange').datepicker({
weekStart: 1,
maxViewMode: 1,
language: "es",
startDate: today,
disableTouchKeyboard: true,
format: {
toDisplay: function(date, format, language) {
var fecha = moment(date).add(1,"day");
date_hidden = fecha;
return fecha.format("dddd DD [de] MMMM, YYYY");
},
toValue: function(date, format, language) {
var fecha = moment(date).add(1,"day");
return moment(fecha).format("DD/MM/YY");
//return moment(date, ["DD.MM.YYYY", "DDMMYYYY"]).toDate();
}
},
}).on("changeDate", function(e){
var fecha_formateada = moment(date_hidden).format("DD/MM/YY");
$(this).next().val(fecha_formateada);
});
}
The daterange works correctly but I want to store the formatted date inside the hidden inputs, as you can see, the format that I want is this: ...format("DD/MM/YY"); but what I get is the display format: format("dddd DD [de] MMMM, YYYY"), also I noticed that $(this) value within this line: $(this).next().val(fecha_formateada); refers to the container div, and not the input that has changed value, so how can I save the date as I want inside the hidden inputs?
I'm not sure what your problem is but by looking at your code I can only guess that you might be in the middle of a race condition.
You're setting the date_hidden variable in Datepicker.toDisplay and then reading from it in the changeDate custom event.
Put a debugger or a console log in both callbacks to make sure you're not in the middle of a race condition.
As for setting the formatted value in the input fields, well I can see in your HTML code that you have selectors that you can use, like the hidden field's ID for example.
Another thing I'd suggest is, instead of setting and reading the date_hidden field in those different callbacks, just call $('#elementID').datepicker('getDate') in the changeDate event handler and do all the transformations you need there, then extract that code and put it in a separate function.

How to restrict date format in date field

I'm trying to implement a function that will bring up an alert box when a date in the wrong format is entered and the submit button is pressed. I have six date fields in my form.
I can't seem to find regex examples that show me how to implement the function in my field inputs only how to do the function itself. I wanted to restrict it to YYYY-MM-DD. Posting here is the last resort for me, I have looked for a long time to no avail. Please can someone help?
function validate_date() {
var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/ ;
if(!(date_regex.test(testDate)))
{
alert('Wrong format!');
return false;
}
}
<input type="text" class="form-control" id="empexpiry" style="width:350px;" placeholder="Nothing on File" name="empexpiry" value=""
If I was you I would use some plugin. There are good vanilla and jQuery plugins to validate forms (e.g. Vanilla, jQuery).
But if you wanna do it by yourself:
Listen to the submit event of the form and validate all your entries using regex
The function to validate could be something like this
function isDateValid (dateStr) {
let isValid = dateStr.match(/[0-9]{4}-[0-9]{2}-[0-9]{2}/)
if (!isValid) return false
const dateObj = new Date(dateStr);
isValid = dateObj != 'Invalid Date'
return isValid
}
And your function to listen the submit could be something like this:
function validateForm (e) {
const input1 = document.getElementById("input1").text
if (!isDateValid(input1)) {
alert('invalid')
e.preventDefault()
return false
}
/* And so on */
}
I found out that the HTML5 pattern attribute was all that was required. Simple!
<input id="date" type="text" pattern="\d{4}-\d{1,2}-\d{1,2}" oninvalid="setCustomValidity('Please make sure the date follows this format: YYYY-MM-DD')" required="required"/>

Knockout.js validation

I'm new to Knockout.js tech where I Googled many site to resolve my situation where I couldn't find a better option.
How to validate a date using Knockout.js? Where in my case if the user typed the date in a wrong format say for e.g if the valid date format is dd-M-yyyy but the user is typing M-dd-yyyy it should automatically convert it to a valid date format.
My sample code is this,
self.dateOfBirth = ko.observable(0).extend({
required: { message: 'Date of Birth is required', params: true },
date: { format: 'dd-M-YYYY' ,
message: 'Not a valid date format',params:true
}
My HTML design is this,
<input class="form-control" id="dateOfBirth" autocomplete="off" placeholder="Date of Birth" type="text" data-bind="value: dateOfBirth, format:'dd-M-YYYY', valueUpdate: 'afterkeydown'">
Take a look at "Writable computed observables" example 3 and example 4 on the official Knockout documentation site.
Example:
this.formattedDate = ko.pureComputed({
read: function () {
return this.date();
},
write: function (value) {
// convert date to dd-M-YYYY, then write the
// raw data back to the underlying "date" observable
value = convertDate(value); // add your own conversion routine
this.date(value); // write to underlying storage
},
owner: this
});
Also consider using the textInput binding, instead of value combined with valueUpdate, for consistent cross-browser handling.
Consider using Knockout event and capture its change event and then use moment.js library to convert it into any date format you like.
In HTML:
<input class="form-control" id="dateOfBirth" autocomplete="off" placeholder="Date of
Birth" type="text" data-bind="value: dateOfBirth, event: { change: dataChanged},
valueUpdate: 'afterkeydown'">
In javascript:
Inside your viewModel
//this function will be called when the date will be changed
self.dataChanged = function(){
//using moment .js here change the format to dd-M-YYYY as desired
var validFormat = moment(self.dateOfBirth()).format('dd-M-yyyy');
self.dateOfBirth(validFormat);
}
for further details check moment.js liberary

Bootstrap datetimepicker get time

I am using Bootstrap datetimepicker in a form insider my Meteor.JS app in order to have two time picker elements. Below is the code I have so far which detect the onChange event for each of the two time picker elements in my form but I can't figure out how to get the selected time? So can someone please tell me how to do so? Thanks
$('.set-start-time').datetimepicker({
pickDate: false
});
$('.set-end-time').datetimepicker({
pickDate: false
});
$('.set-end-time').on("dp.change",function (e) {
var now = $('.set-start-time').data("DateTimePicker").getDate();
var then = $('.set-end-time').data("DateTimePicker").getDate();
//Above code won't return time...
});
I hope this helps some one.
HTML
<div name="startTime" class="input-group time">
<input class="form-control" type="text" value="" >
<span class="input-group-addon"><i class="fa fa-clock-o"></i></span>
</div>
JS
$('.time').datetimepicker({
format: 'LT'
}).on("dp.change",function(e){
var date = e.date;//e.date is a moment object
var target = $(e.target).attr('name');
console.log(date.format("HH:mm:ss"))//get time by using format
})
e.date is a moment object thus time can derived by using format("HH:mm:ss")

Javascript - loop through datepickers and set date

I don't know Javascript at all. I have a form where there can be any number of datepicker textboxes. When the user selects a date in the first datepicker textbox, then I want all the remaining datepicker textboxes to have that same date.
Does this require a function?
Edit: I tried to create a function, but I don't know javascript at all!
function UpdateValuationDates(event) {
$valuationDatePicker = $(event.target);
var valuationDate = $valuationDatePicker.datepicker("getDate");
if (valuationDate != null) {
//loop through all items
document.getElementById("dateValuationDate").Text
$valuationDatePicker.datepicker("setDate", valuationDate);
$valuationDatePicker.trigger('change');
}
}
So I think this can be ignored. I have also read that there is a datepicker on selected event:
$(".date").datepicker({
onSelect: function(dateText) {
display("Selected date: " + dateText + "; input's current value: " + this.value);
}
});
So I guess I need to edit this code to populate the rest of the textboxes, but how to find out at runtime how many there are?
The HMTL has a repeater with the datepicker repeated x number of times:
<abc:DatePicker runat="server" ID="dateValuationDate"
With the help of html's input type=date and some basic classes' knowledge, you can do that.. Considering you have following Date pickers:
<input type="date" class="dateTime">
<input type="date" class="dateTime">
<input type="date" class="dateTime">
Now you simply need to listen to a change in any one of there values:
$(".dateTime").on("change", function(){
and when the change occurs, get the changed value and set all other date pickers to that new value:
$(".dateTime").val($(this).val());
So it'll be something like this:
$(document).ready(function(){
$(".dateTime").on("change", function(){
$(".dateTime").val($(this).val());
});
});
See the DEMO here
EDIT: Considering you're new to JavaScript, here's how i'm getting the reference to all those elements, through .className, as they all have same class name so for each event (change, update value) they all will be referenced.

Categories

Resources