The bounty expires in 3 days. Answers to this question are eligible for a +50 reputation bounty.
Alex T wants to draw more attention to this question.
I am using yup to validate the values in the input field:
const dateToCheck = yup
.date()
.nullable()
.transform((curr, orig) => (orig === '' ? null : curr))
.required()
.min(minDate, 'Date cannot be this early')
.max(maxDate, 'Date too much in the future')
.test('format', 'Date is invalid', date => (date?.getFullYear() ?? 0) <= 9999)
I have been trying to figure out how to check if the input date has the correct format?
Because of how yup works, both 01.01.2000 and 2000/01/01 will pass date validation but I would like to be able to only dd.MM.yyyy format to pass or only yyyy/MM/dd format to pass not both and then every other format which would be valid otherwise be labelled as invalid instead. What is the correct way to do it in yup?
As an alternative approach to showing an error when the format is incorrect, you can change the input date to the format you want. Following example will parse all dates to yyyy-MM-dd format:
import { parse, isDate } from "date-fns";
function parseDateString(value, originalValue) {
const parsedDate = isDate(originalValue)
? originalValue
: parse(originalValue, "yyyy-MM-dd", new Date());
return parsedDate;
}
Related
I'm using ion-datetime in ionic4 using NgModel to bind to a property, however, no matter what options I include in format, I always get the time with the timestamp included. ¿How can I remove timestamp from result so the final value of my property is something like "2019-04-22" instead of "2019-04-22T08:45:41.243-05:00"?
I tried: but, I'm still getting the timestamp
<ion-datetime max="2030" min="2019" [(ngModel)]="mydate" display-format="MMM DD, YYYY"></ion-datetime>
I expect the result to be like: "2019-04-22", but I keep getting: "2019-04-22T08:45:41.243-05:00"
If you want only date then I think split() method might works,beacause value we get from ion-datetime is a string.So we use split method which split string and convert it to an array,and you can get date or time which thing you want with the help of index as follow:
var dateFormat = mydate.split('T')[0];
console.log(dateFormat);
// 2019-04-22
You can format the date with Moment.js.
<ion-datetime displayFormat="MMM DD, YYYY" max="2030" min="2019" [(ngModel)]="mydate" (ionChange)="doSomething(this.mydate)"></ion-datetime>
import * as moment from 'moment';
doSomething(date) {
console.log('date', moment(date).format('YYYY-MM-DD')); // 2019-04-22
}
You can use custom picker options to set custom buttons, it returns an object with all the variables in separate keys, so it makes it easier to edit the way you want it to display
To do so, you would insert this in your ion-datetime
[pickerOptions]="customPickerOptions"
and in your .ts file
this.customPickerOptions = {
buttons: [
{
text: 'Save',
handler: (time) => {
console.log('time', time);
}
},
{
text: 'Cancel',
handler: e => {
modalCtrl.dismiss(e)
}
}
]
}
Hope this helps
<ion-datetime
displayFormat="DD.MM.YYYY"
presentation="date"
[(ngModel)]="date"></ion-datetime>
<div>{{date.split('T')[0]}}</div>
in Ts file
data:any='';
You can use moment.js
in your file.page.html
<ion-datetime [(ngModel)]="mydate" placeholder=""></ion-datetime>
in your file.page.ts
import moment from 'moment';
<!-- to pass data to your API -->
mydate = moment(mydate).format('YYYY-MM-DD');
<!-- to view in console -->
yourFunction(mydate) {
console.log('date', moment(mydate).format('YYYY-MM-DD'));
}
May this answer helps. I understand how frustrating it can be to find the answer we are looking for.
Edit2: toLocaleFormat is not widely accepted. Here is a post on alternatives. You could just split it around the T.
const dateArray = fullDateString.split('T');
if (dateArray.length > 0){
const partYouWant = dateArray[0];
}
Edit: From the Ionic docs
It's also important to note that neither the displayFormat or
pickerFormat can set the datetime value's output, which is the value
that is set by the component's ngModel. The format's are merely for
displaying the value as text and the picker's interface, but the
datetime's value is always persisted as a valid ISO 8601 datetime
string.
Here is a better answer:
const dateObject = new Date(this.mydate);
const dateString = dateObject.toLocaleFormat('%Y-%m-%d');
An input for new Date can be a date string defined as:
String value representing a date. The string should be in a format
recognized by the Date.parse() method (IETF-compliant RFC 2822
timestamps and also a version of ISO8601).
I'm guessing you are trying to access this.mydate in your code.
You have several options, best represented by this stack overflow post.
this.mydate.toLocaleFormat('%Y-%m-%d');
This function will take a Date object and convert it to the string in the format you requested. All the options you can put in the options are here.
There are also plenty of other options shown in the stack overflow post above.
install date-fns by npm i --save date-fns
import {format} from "date-fns"; in your .ts file
let date_x = "2019-11-30T14:42:30.951+08:00";
format(new Date(date_x), "yyyy-MM-dd");
you should get as result in console => '2019-11-29'
This is the best way to get the exactly time
First Create the $event method like this
changeTime(e) {
this.sentTempTime = "";
let hoursMinutes = e.split(':');
this.sentTime = this.formatTime(hoursMinutes);
}
after that create the formatTime() method like this
formatAMPM(date) {
var hours = date[0].toString().split('T'); //22
var minutes = date[1]; //11
var ampm = hours[1] >= 12 ? 'pm' : 'am'; //22 >=12 yes == pm
hours = hours[1] >= 12 ? hours[1] - 12 : hours[1]; //22 >= 12 ? 22-12=10
var strTime = hours + ':' + minutes + ampm;
return strTime;
}
after that you can able to get the time like this 08:15pm
In Ionic 6 you just need the presentation property.
Set it to date and it will only render the date picker, without the time picker.
<ion-datetime presentation="date"></ion-datetime>
See the presentation property in the docs for more details.
How to specify the format of the dateFilter in Webix datatable?
I have a grid where dates are formatted to "%d.%m.%Y":
columns:[
{ id:"date", header:[{ content:"dateFilter" }], width:160, format:myFormat }
]
where myFormat is webix.Date.dateToStr("%d.%m.%Y"); The result is dd.mm.yyyy
Here's a snippet with the similar grid: http://webix.com/snippet/1ec86aa8
The point is that the dateFilter still requires the full dates as %m-%d-%Y (mm-dd-yyyy)
So I'm looking for a way to change this predefined pattern. Any suggestion are appreciated.
dateFilter convert user entered date from str to date using webix.i18n.dateFormatDate
By the way, it does more thing. For exemple you can enter "<1996" and so it will not convert using the above method date but extract the year.
Then it convert the guessed date to an interger and perform an interger comparison with data's dates
Sadly "webix.i18n.dateFormatDate" use the webix.i18n.dateFormat which depend the locale to convert string to date. and there is no way to customize the format used by dateFilter.
A solution for you is to create a custom filter which do the same job as dateFilter but using your own date convertion :
Here is a modified webix code of dateFilter :
webix.ui.datafilter.myDateFilter = webix.extend({
format:function(value){
if (value === "") return "";
var date = new Date();
if (value.indexOf("today") != -1){
date = webix.Date.dayStart(date);
} else if (value.indexOf("now") == -1){
var parts = value.match(/[0-9]+/g);
if (!parts||!parts.length) return "";
if (parts.length < 3){
parts.reverse();
date = new Date(parts[0], (parts[1]||1)-1, 1);
} else
// Change here
date = webix.Date.strToDate("%d.%m.%Y")(value.replace(/^[>< =]+/,""));
}
return date.valueOf();
}
}, webix.ui.datafilter.numberFilter);
Updated snippet : http://webix.com/snippet/20c0175a
I have a kendo date picker that is constructed as follows:
$("#date").kendoDatePicker({
format: "yyyy-MM-dd",
footer: " ",
parseFormats: ["MM/dd/yyyy", "dd/MM/yyyy"]
});
I would like to use the kendo validator to validate that the date contains a valid date in the format of yyyy-MM-dd. I have tried this:
<input type="date" id="date" placeholder="yyyy-mm-dd" name="date" required data-required-msg="Please enter a date." data-date-msg="Please enter a valid date."/>
While the validator does correctly validate the "required" condition, it does not seem to validate that the date is in the correct format or is a valid date. For instance, "abc" passes as a valid date as does 2013-18-85. How can I use the validator to ensure a valid date in the correct format?
If you want to validate a date you need to define a rule (no built-in rule).
Try defining:
$("#date").kendoValidator({
rules: {
date: function (input) {
var d = kendo.parseDate(input.val(), "yyyy-MM-dd");
return d instanceof Date;
}
}
});
NOTE: Remember that KendoUI first uses parseFormats option for parsing the date, then converts it to the format option and finally run validations. That's why I use in validation yyyy-MM-dd and not ["MM/dd/yyyy", "dd/MM/yyyy"].
The answer is:
<script src="#Url.Content("~/Scripts/kendo/2015.2.805/kendo.aspnetmvc.min.js")"></script>
<script type="text/javascript">
kendo.ui.validator.rules.mvcdate = function (input) {
//use the custom date format here
//kendo.parseDate - http://docs.telerik.com/kendo-ui/api/javascript/kendo#methods-parseDate
return !input.is("[data-val-date]") || input.val() === "" || kendo.parseDate(input.val(), "#(MvcApplication.AppCulture.DateTimeFormat.ShortDatePattern)") !== null;
};
</script>
Here is more information: http://docs.telerik.com/kendo-ui/aspnet-mvc/validation
Cheers
Assume in my text box user enter like
18-06-2010 ,
Validation RULE if date is greater then current date then program should through the validation error like ,
PELASE ENTER PAST OR CURRENT DATE, DONT CHOOSE FUTURE DATE ,
Thanks
The date format you've specified is not recognized by javascript. Here's a script that makes some minor validity checking, but still some rough assumptions that the value entered conforms to the format above, and tries to construct the date string '2010/06/08' out of that.
var txtDate = document.getElementById('myTextBox').value;
var dateParts = txtDate.split('-');
if(dateParts.length != 3) {
alert('invalid date!');
return false;
}
var testDate = new Date(dateParts[2] + '/' + dateParts[1] + '/' + dateParts[0]);
if(isNaN(testDate.getDate())) {
alert('invalid date!');
return false;
}
Implement further error checking as you see fit. Once you know testDate is a date, you can compare it the current date: testDate > new Date()
I have an HTML text field. I want to validate via JavaScript that the value entered is a valid date in the form of "MM/DD/YY" or "MM/D/YY" or "MM/DD/YYYY" or "MM/D/YYYY". Is there a function that does this?
I sort of assumed there was something like isNaN but I don't see anything. Is it true that JavaScript can't validate dates?
You could use javascript's own Date object to check the date. Since the date object allows some mucking around with the month and day values (for example March 32 would be corrected to April 1), you can just check that the date you create matches the one you put in. You could shorten this if you want, but it's longer for clarity.
function checkDate(m,d,y)
{
try {
// create the date object with the values sent in (month is zero based)
var dt = new Date(y,m-1,d,0,0,0,0);
// get the month, day, and year from the object we just created
var mon = dt.getMonth() + 1;
var day = dt.getDate();
var yr = dt.getYear() + 1900;
// if they match then the date is valid
if ( mon == m && yr == y && day == d )
return true;
else
return false;
}
catch(e) {
return false;
}
}
Is it true that JavaScript can't validate dates?
No.
Is there a function that does this?
No.
You will need to write your own validation function to parse the date format (regex comes to mind) and then determine if it is valid within your specific criteria.
Check out http://momentjs.com/. Using it, this snippet
moment(yourCandidateString, 'MM-DD-YYYY').isValid()
should do the job.
This is what I use to validate a date.
Date.parse returns NaN for invalid dates.
This supports both date-only and date+time formats.
Hope this helps.
var msg;
var str = "2013-12-04 23:10:59";
str = "2012/12/42";
var resp = Date.parse(str);
if(!isNaN(resp)) { msg='valid date'; } else { msg='invalid date'; }
console.log(msg);
If you want to venture into the realms of JQuery there are plenty of validation plugins that include date validation. This plugin is one I've used a few times and has served me well.
I use Bootstrap Datepicker. One of the options with the text box disabled should do the trick.
http://www.eyecon.ro/bootstrap-datepicker/
<input type="text" id="dateinput"/>
<script type="text/javascript">
$(#"dateinput").datepicker({
buttonImage: "images/calendar.png",
dateFormat: "yyyy-MMM-dd"
});
function validateDate() {
if ($(#"dateinput").val().trim() == "") {
// Is a blank date allowed?
return true;
}
var oldVal = $(#"dateinput").val(); // Current value in textbox
// Now use jQueryUI datepicker to try and set the date with the current textbox value
$(#"dateinput").datepicker("setDate",$(#"dateinput").val());
// Check if the textbox value has changed
if (oldVal != $(#"dateinput").val()) {
// The datepicker will set something different if the date is invalid
$(#"dateinput").val(oldVal); // Set the textbox back to the invalid date
alert ("date was invalid");
return false;
} else {
// If nothing changed, the date must be good.
return true;
}
}
</script>
There does not appear to be a build-in function which does that. However, this code is probably what you're looking for:
<script type="text/javascript">
/**--------------------------
//* Validate Date Field script- By JavaScriptKit.com
//* For this script and 100s more, visit http://www.javascriptkit.com
//* This notice must stay intact for usage
---------------------------**/
function checkdate(input){
var validformat=/^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
var returnval=false
if (!validformat.test(input.value))
alert("Invalid Date Format. Please correct and submit again.")
else{ //Detailed check for valid date ranges
var monthfield=input.value.split("/")[0]
var dayfield=input.value.split("/")[1]
var yearfield=input.value.split("/")[2]
var dayobj = new Date(yearfield, monthfield-1, dayfield)
if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
else
returnval=true
}
if (returnval==false) input.select()
return returnval
}
</script>
Source: http://www.javascriptkit.com/script/script2/validatedate.shtml
Have you googled for something like javascript date validation? It shows up some good information, and a working code example here.
I suggest you a couple of solutions.
guide the user input with a date picker. This way you can control the input format. jQueryui datepicker is a popular implementation.
use a js library to manage datetime data type (not an actual datatype in Javascript!!). I suggest you date.js.
Similar to this answer, Date can be used to check if the parsed version of the string corresponds to the original date string.
> datestring_valid = "2020-02-29";
> parsed_Date = new Date(datestring_valid);
> parsed_Date.toISOString().slice(0,10) == datestring_valid;
true
> datestring_invalid = "2021-02-29";
> parsed_Date = new Date(datestring_invalid);
> parsed_Date.toISOString().slice(0,10) == datestring_invalid;
false
NB: This requires the date string to be ISO formatted.
The reason this works is, that Date parses some invalid dates into something valid as in the example above. However, supplying "2020-01-32" into Date will result in the result being "Invalid Date" that isNaN.
A function that handles all of this is the following:
function isValidDateString(datestring) {
parsed_Date = new Date(datestring);
return (parsed_Date.toISOString().slice(0,10) == datestring) && !isNaN(parsed_Date)
};
> isValidDateString(datestring_valid)
true
> isValidDateString(datestring_invalid)
false