I'm working on an input form that includes a credit card expiration date for only Visa and Mastercard. These two restrict the expiration date to MM/YY. I'm using the following script elsewhere on the form to automatically introduce slashes as the user types in their birth date:
$(function() {
var date = document.getElementById('ccexp');
function checkValue(str, max) {
if (str.charAt(0) !== '0' || str == '00') {
var num = parseInt(str);
if (isNaN(num) || num <= 0 || num > max) num = 1;
str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString();
}
return str;
}
date.addEventListener('keydown', function(e) {
this.type = 'text';
var input = this.value;
var key = e.keyCode || e.charCode;
if (key == 8 || key == 46) // checks if backspace or delete is being pressed
return false;
if (/\D\/$/.test(input)) input = input.substr(0, input.length - 1);
var values = input.split('/').map(function(v) {
return v.replace(/\D/g, '')
});
if (values[0]) values[0] = checkValue(values[0], 12); // validates month 1-12
if (values[1]) values[1] = checkValue(values[1], 31); // validates day 1-31
var output = values.map(function(v, i) {
return v.length == 2 && i < 2 ? v + '/' : v;
});
this.value = output.join('').substr(0, 10);
});
});
(The requirements on this project are for users to type in dates, rather than use a date picker). I'd like to use a version of this script to look for MM/YY, but I really don't know how to parse this well enough myself.
Related
I have this code and I have to remove the year part of it, it's a formatter for date values in a form, it has to be "DD/MM" but it is "MM/DD/YYYY" can someone help me?
<input type="text" name="datada" id="dtDataDa" placeholder="" value="%dtDataDa%"/>
THIS IS THE CODE I HAVE TO MODIFY
var date = document.getElementById('dtDataDa');
function checkValue(str, max) {
if (str.charAt(0) !== '0' || str == '00') {
var num = parseInt(str);
if (isNaN(num) || num <= 0 || num > max) num = 1;
str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString();
};
return str;
};
date.addEventListener('input', function (e) {
this.type = 'text';
var input = this.value;
if (/\D\/$/.test(input)) input = input.substr(0, input.length - 3);
var values = input.split('/').map(function (v) {
return v.replace(/\D/g, '')
});
if (values[0]) values[0] = checkValue(values[0], 12);
if (values[1]) values[1] = checkValue(values[1], 31);
var output = values.map(function (v, i) {
return v.length == 2 && i < 2 ? v + ' / ' : v;
});
this.value = output.join('').substr(0, 14);
});
date.addEventListener('blur', function (e) {
this.type = 'text';
var input = this.value;
var values = input.split('/').map(function (v, i) {
return v.replace(/\D/g, '')
});
var output = '';
if (values.length == 3) {
var year = values[2].length !== 4 ? parseInt(values[2]) + 2000 : parseInt(values[2]);
var month = parseInt(values[0]) - 1;
var day = parseInt(values[1]);
var d = new Date(year, month, day);
if (!isNaN(d)) {
document.getElementById('result').innerText = d.toString();
var dates = [d.getMonth() + 1, d.getDate(), d.getFullYear()];
output = dates.map(function (v) {
v = v.toString();
return v.length == 1 ? '0' + v : v;
}).join(' / ');
};
};
this.value = output;
});
It makes the form insert only real digits, for the month (1s part) numbers until 12, for the days (2nd part) numbers until 31 and for the year (3rd part) there is no rule.. I would like to have only the month and days part of it so that an example would look like "06/18"
Here you can see it https://codepen.io/user23xx/pen/VdarOL?editors=1010
Thank you for your time.
It's actually quite simple to modify from the code you've shared.
Look for the comments at addEventListener
date.addEventListener('input', function (e) {
this.type = 'text';
var input = this.value;
if (/\D\/$/.test(input)) input = input.substr(0, input.length - 3);
var values = input.split('/').map(function (v) {
return v.replace(/\D/g, '')
});
if (values[0]) values[0] = checkValue(values[0], 31); //Put 31 instead of 12
if (values[1]) values[1] = checkValue(values[1], 12); //Put 12 instead of 31
var output = values.map(function (v, i) {
return v.length == 2 && i < 2 ? v + ' / ' : v;
});
this.value = output.join('').substr(0, 7); //Update to 7 instead of 14 because full length you want is 7
});
Next we want to update the blur method as below
if (!isNaN(d)) {
document.getElementById('result').innerText = d.toString();
var dates = [d.getDate(),d.getMonth() + 1];//Remove the year part
output = dates.map(function (v) {
v = v.toString();
return v.length == 1 ? '0' + v : v;
}).join(' / ');
};
UPDATES:
date.addEventListener('blur', function (e) {
this.type = 'text';
var input = this.value;
var values = input.split('/').map(function (v, i) {
return v.replace(/\D/g, '')
});
var output = '';
if (values.length == 2) {
var dates = [values[0], values[1]];
output = dates.map(function (v) {
v = v.toString();
return v.length == 1 ? '0' + v : v;
}).join(' / ');
};
this.value = output;
});
This question already has answers here:
How to format a number with commas as thousands separators?
(50 answers)
Closed 6 years ago.
I have a script where I pass it a string, and it'll return that string formatted as dollars. So if I send it "10000" it'll return "$10,000.00" Now the problem is that when I send it "1000000" ($1 million) it returns "$1,000.00" because it's only setup to parse based on one set of zeros. Here's my script, how can I adjust it to account for two sets of zeros ($1 million) ??
String.prototype.formatMoney = function(places, symbol, thousand, decimal) {
if((this).match(/^\$/) && (this).indexOf(',') != -1 && (this).indexOf('.') != -1) {
return this;
}
places = !isNaN(places = Math.abs(places)) ? places : 2;
symbol = symbol !== undefined ? symbol : "$";
thousand = thousand || ",";
decimal = decimal || ".";
var number = Number(((this).replace('$','')).replace(',','')),
negative = number < 0 ? "-" : "",
i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return negative + symbol + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : ""); };
Thanks in advance for any useful information!
function formatMoney(number) {
return number.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
}
console.log(formatMoney(10000)); // $10,000.00
console.log(formatMoney(1000000)); // $1,000,000.00
Give this a shot it looks for a decimal separator but you can remove that part if youd like:
{
number = parseFloat(number);
//if number is any one of the following then set it to 0 and return
if (isNaN(number)) {
return ('0' + '{!decimalSeparator}' + '00');
}
number = Math.round(number * 100) / 100; //number rounded to 2 decimal places
var numberString = number.toString();
numberString = numberString.replace('.', '{!decimalSeparator}');
var loc = numberString.lastIndexOf('{!decimalSeparator}'); //getting position of decimal seperator
if (loc != -1 && numberString.length - 2 == loc) {
//Adding one 0 to number if it has only one digit after decimal
numberString += '0';
} else if (loc == -1 || loc == 0) {
//Adding a decimal seperator and two 00 if the number does not have a decimal separator
numberString += '{!decimalSeparator}' + '00';
}
loc = numberString.lastIndexOf('{!decimalSeparator}'); //getting position of decimal seperator id it is changed after adding 0
var newNum = numberString.substr(loc, 3);
// Logic to add thousands seperator after every 3 digits
var count = 0;
for (var i = loc - 1; i >= 0; i--) {
if (count != 0 && count % 3 == 0) {
newNum = numberString.substr(i, 1) + '{!thousandSeparator}' + newNum;
} else {
newNum = numberString.substr(i, 1) + newNum;
}
count++;
}
// return newNum if youd like
};
i have a textfield, which is there for a Date in YYYY-MM-DD format. What I want to do is to check for the correctness of the date.
My concept would be:
deadline = document.getElementById("Deadline").value;
if (deadline[0] == "0" ||
deadline[0] == "1" ||
deadline[0] == "2" ||
deadline[0] == "3" ||
deadline[0] == "4" ||
deadline[0] == "5" ||
deadline[0] == "6" ||
deadline[0] == "7" ||
deadline[0] == "8" ||
deadline[0] == "9" ){
if(deadline[1] == "0" || ...){
if(deadline[2] == "0" || ...){
...
}else{alert("Wrong Format!")}
}
}
}
Is there a more efficient way of doing this?
Use a Regex:
// yyyy-mm-dd
var re = /^\d{4}-\d{1,2}-\d{1,2}$/;
alert(re.test("2001-11-02"));
While using a RegExp will give you a rough idea about the correctness of format, it will not check the validity of the values. A better approach may be something like this.
function inRange (val, min, max) {
return val >= min && val <= max;
}
var deadLine = document.getElementById('deadline'),
out = document.getElementById('out');
deadLine.addEventListener('change', function (e) {
var text = e.target.value,
valid,
parts,
year,
month,
day,
result;
if ((/^\d{1,4}-\d{2}-\d{2}$/).test(text)) {
parts = text.split('-');
year = parts[0];
month = parts[1];
day = parts[2],
valid = inRange (year, 0, 9999) &&
inRange (month, 1, 12) &&
inRange (day, 0, 31) &&
day == new Date(year, month - 1, day).getDate();
}
if (valid) {
result = 'Correct Format and date!';
} else {
result = 'Wrong Format or date!';
}
out.appendChild(document.createTextNode(result + '\n'));
}, false);
<input id="deadline" type="text"></input>
<pre id="out"></pre>
You should use regular expression. Check the code at https://regex101.com/r/iO0pY2/1. Here how you can use it:
var str = '2015-02-05'
var re = /^(\d{4})\-(\d{1,2})\-(\d{1,2})$/
var valid = re.test(str);
User input time in the decimal format.
like
0.00 //Incorrect
1.54 //Correct value
1.60 //Incorrect value
1.59 //correct value
I have tried to make a regular expression function but it is showing incorrect for all values
var regex = /^[0-9]\d*(((,?:[1-5]\d{3}){1})?(\.?:[0-9]\d{0,2})?)$/;
if (args.Value != null || args.Value != "") {
if (regex.test(args.Value)) {
//Input is valid, check the number of decimal places
var twoDecimalPlaces = /\.\?:[1-5]\d{2}$/g;
var oneDecimalPlace = /\.\?:[0-9]\d{1}$/g;
var noDecimalPlacesWithDecimal = /\.\d{0}$/g;
if (args.Value.match(twoDecimalPlaces)) {
//all good, return as is
args.IsValid = true;
return;
}
if (args.Value.match(noDecimalPlacesWithDecimal)) {
//add two decimal places
args.Value = args.Value + '00';
args.IsValid = true;
return;
}
if (args.Value.match(oneDecimalPlace)) {
//ad one decimal place
args.Value = args.Value + '0';
args.IsValid = true;
return;
}
//else there is no decimal places and no decimal
args.Value = args.Value + ".00";
args.IsValid = true;
return;
} else
args.IsValid = false;
} else
args.IsValid = false;
It's probably easier to do working with a number:
var time = (+args.Value).toFixed(2); // convert to float with 2 decimal places
if (time === args.Value) {
// it's a valid number format
if (time !== 0.0 && time < 24) {
// the hours are valid
if (time % 1 < 0.6) {
// the minutes are valid
}
}
}
You can collapse all that up into a nice one-liner:
if (time === args.Value && time !== 0.0 && time < 24 && time % 1 < 0.6) {
}
and even a boolean/ternary
var valid = time === args.Value && time !== 0.0 && time < 24 && time % 1 < 0.6;
alert( time === args.Value && time !== 0.0 && time < 24 && time % 1 < 0.6 ? 'valid' : 'invalid' );
I am attempting to validate a date in this format: (yyyy-mm-dd). I found this solution but it is in the wrong format for what I need, as in: (mm/dd/yyyy).
Here is the link to that solution: http://jsfiddle.net/ravi1989/EywSP/848/
My code is below:
function isDate(txtDate)
{
var currVal = txtDate;
if(currVal == '')
return false;
var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/; //Declare Regex
var dtArray = currVal.match(rxDatePattern); // is format OK?
if (dtArray == null)
return false;
//Checks for mm/dd/yyyy format.
dtMonth = dtArray[1];
dtDay= dtArray[3];
dtYear = dtArray[5];
if (dtMonth < 1 || dtMonth > 12)
return false;
else if (dtDay < 1 || dtDay> 31)
return false;
else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31)
return false;
else if (dtMonth == 2)
{
var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
if (dtDay> 29 || (dtDay ==29 && !isleap))
return false;
}
return true;
}
What regex pattern can I use for this that will account for invalid dates and leap years?
I expanded just slightly on the isValidDate function Thorbin posted above (using a regex). We use a regex to check the format (to prevent us from getting another format which would be valid for Date). After this loose check we then actually run it through the Date constructor and return true or false if it is valid within this format. If it is not a valid date we will get false from this function.
function isValidDate(dateString) {
var regEx = /^\d{4}-\d{2}-\d{2}$/;
if(!dateString.match(regEx)) return false; // Invalid format
var d = new Date(dateString);
var dNum = d.getTime();
if(!dNum && dNum !== 0) return false; // NaN value, Invalid date
return d.toISOString().slice(0,10) === dateString;
}
/* Example Uses */
console.log(isValidDate("0000-00-00")); // false
console.log(isValidDate("2015-01-40")); // false
console.log(isValidDate("2016-11-25")); // true
console.log(isValidDate("1970-01-01")); // true = epoch
console.log(isValidDate("2016-02-29")); // true = leap day
console.log(isValidDate("2013-02-29")); // false = not leap day
You could also just use regular expressions to accomplish a slightly simpler job if this is enough for you (e.g. as seen in [1]).
They are build in into javascript so you can use them without any libraries.
function isValidDate(dateString) {
var regEx = /^\d{4}-\d{2}-\d{2}$/;
return dateString.match(regEx) != null;
}
would be a function to check if the given string is four numbers - two numbers - two numbers (almost yyyy-mm-dd). But you can do even more with more complex expressions, e.g. check [2].
isValidDate("23-03-2012") // false
isValidDate("1987-12-24") // true
isValidDate("22-03-1981") // false
isValidDate("0000-00-00") // true
[1]
Javascript - Regex to validate date format
[2] http://www.regular-expressions.info/dates.html
Since jQuery is tagged, here's an easy / user-friendly way to validate a field that must be a date (you will need the jQuery validation plugin):
html
<form id="frm">
<input id="date_creation" name="date_creation" type="text" />
</form>
jQuery
$('#frm').validate({
rules: {
date_creation: {
required: true,
date: true
}
}
});
DEMO + Example
UPDATE: After some digging, I found no evidence of a ready-to-go parameter to set a specific date format.
However, you can plug in the regex of your choice in a custom rule :)
$.validator.addMethod(
"myDateFormat",
function(value, element) {
// yyyy-mm-dd
var re = /^\d{4}-\d{1,2}-\d{1,2}$/;
// valid if optional and empty OR if it passes the regex test
return (this.optional(element) && value=="") || re.test(value);
}
);
$('#frm').validate({
rules: {
date_creation: {
// not optional
required: true,
// valid date
date: true
}
}
});
This new rule would imply an update on your markup:
<input id="date_creation" name="date_creation" type="text" class="myDateFormat" />
Here's the JavaScript rejex for YYYY-MM-DD format
/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/
try this Here is working Demo:
$(function() {
$('#btnSubmit').bind('click', function(){
var txtVal = $('#txtDate').val();
if(isDate(txtVal))
alert('Valid Date');
else
alert('Invalid Date');
});
function isDate(txtDate)
{
var currVal = txtDate;
if(currVal == '')
return false;
var rxDatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/; //Declare Regex
var dtArray = currVal.match(rxDatePattern); // is format OK?
if (dtArray == null)
return false;
//Checks for mm/dd/yyyy format.
dtMonth = dtArray[3];
dtDay= dtArray[5];
dtYear = dtArray[1];
if (dtMonth < 1 || dtMonth > 12)
return false;
else if (dtDay < 1 || dtDay> 31)
return false;
else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31)
return false;
else if (dtMonth == 2)
{
var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
if (dtDay> 29 || (dtDay ==29 && !isleap))
return false;
}
return true;
}
});
changed regex is:
var rxDatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/; //Declare Regex
I recommend to use the
Using jquery validation plugin and jquery ui date picker
jQuery.validator.addMethod("customDateValidator", function(value, element) {
// dd-mm-yyyy
var re = /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$/ ;
if (! re.test(value) ) return false
// parseDate throws exception if the value is invalid
try{jQuery.datepicker.parseDate( 'dd-mm-yy', value);return true ;}
catch(e){return false;}
},
"Please enter a valid date format dd-mm-yyyy"
);
this.ui.form.validate({
debug: true,
rules : {
title : { required : true, minlength: 4 },
date : { required: true, customDateValidator: true }
}
}) ;
Using Jquery and date picker just create a function with
// dd-mm-yyyy
var re = /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$/ ;
if (! re.test(value) ) return false
// parseDate throws exception if the value is invalid
try{jQuery.datepicker.parseDate( 'dd-mm-yy', value);return true ;}
catch(e){return false;}
You might use only the regular expression for validation
// dd-mm-yyyy
var re = /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$/ ;
return re.test(value)
Of course the date format should be of your region
moment(dateString, 'YYYY-MM-DD', true).isValid() ||
moment(dateString, 'YYYY-M-DD', true).isValid() ||
moment(dateString, 'YYYY-MM-D', true).isValid();
Just use Date constructor to compare with string input:
function isDate(str) {
return 'string' === typeof str && (dt = new Date(str)) && !isNaN(dt) && str === dt.toISOString().substr(0, 10);
}
console.log(isDate("2018-08-09"));
console.log(isDate("2008-23-03"));
console.log(isDate("0000-00-00"));
console.log(isDate("2002-02-29"));
console.log(isDate("2004-02-29"));
Edited: Responding to one of the comments
Hi, it does not work on IE8 do you have a solution for – Mehdi Jalal
function pad(n) {
return (10 > n ? ('0' + n) : (n));
}
function isDate(str) {
if ('string' !== typeof str || !/\d{4}\-\d{2}\-\d{2}/.test(str)) {
return false;
}
var dt = new Date(str.replace(/\-/g, '/'));
return dt && !isNaN(dt) && 0 === str.localeCompare([dt.getFullYear(), pad(1 + dt.getMonth()), pad(dt.getDate())].join('-'));
}
console.log(isDate("2018-08-09"));
console.log(isDate("2008-23-03"));
console.log(isDate("0000-00-00"));
console.log(isDate("2002-02-29"));
console.log(isDate("2004-02-29"));
Rearrange the regex to:
/^(\d{4})([\/-])(\d{1,2})\2(\d{1,2})$/
I have done a little more than just rearrange the terms, I've also made it so that it won't accept "broken" dates like yyyy-mm/dd.
After that, you need to adjust your dtMonth etc. variables like so:
dtYear = dtArray[1];
dtMonth = dtArray[3];
dtDay = dtArray[4];
After that, the code should work just fine.
Working Demo fiddle here Demo
Changed your validation function to this
function isDate(txtDate)
{
return txtDate.match(/^d\d?\/\d\d?\/\d\d\d\d$/);
}
You can use this one it's for YYYY-MM-DD. It checks if it's a valid date and that the value is not NULL. It returns TRUE if everythings check out to be correct or FALSE if anything is invalid. It doesn't get easier then this!
function validateDate(date) {
var matches = /^(\d{4})[-\/](\d{2})[-\/](\d{2})$/.exec(date);
if (matches == null) return false;
var d = matches[3];
var m = matches[2] - 1;
var y = matches[1] ;
var composedDate = new Date(y, m, d);
return composedDate.getDate() == d &&
composedDate.getMonth() == m &&
composedDate.getFullYear() == y;
}
Be aware that months need to be subtracted like this: var m = matches[2] - 1; else the new Date() instance won't be properly made.