I want to have my calculator to display "0" when cleared or no other numbers have been entered but when I start adding numbers I want the 0 to be replaced. Currently when I enter any number it replaces the number on the display to the number entered.
this.currentDisplay = "0"
numberData(number) {
if (number === "." && this.currentDisplay.includes("."))
return
if (this.currentDisplay = "0") {
this.currentDisplay = this.currentDisplay.toString().replace("0", number.toString())
}
else {
this.currentDisplay = this.currentDisplay.toString() + number.toString()
}
}
You have an error on the this condition:
if (this.currentDisplay == "0") {
...
}
In your code you are assigning this.currentDisplay = 0, you should compare with == or better === to compare the types of the variables too.
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.
Hi all I need an if and else statement that checks if two fields which are min and max are numbers and these numbers can be whole numbers like 0 or 12 or they could be 0.50 to 1,300.99 does anyone know how to check for numbers my code is in the following format:
jQuery:
$(document).ready(function(e) {
$('#price_range').click(function(e) {
var price_min = $('#min').val();
var price_max = $('#max').val();
var error_msg = "";
if(price_min.macth(.../) && price_max.match(.../)) {
error_msg = "Please enter a valid number."
}else if(price_min > price_max) {
error_msg = "Min is greater than max."
}
}
I think you don't need regex for number check. You can do a parseFloat and loose compare the results with the initial value.
function isNumber(number) {
var i;
return (!isNaN(i = parseFloat(number)) && number == i);
}
var data = [
"hello.world",
"33",
"25.",
"2.345",
"h.50",
".50",
];
var regex = /^(?:\d+)?(?:\.)?(?:\d+)?$/;
for (var i=0; i<data.length; ++i) {
if (data[i].match(regex)) {
console.log(data[i] + " is a number!");
}
else {
console.log(data[i] + ": NOT");
}
}
--output:--
hello.world: NOT
33 is a number!
25. is a number!
2.345 is a number!
h.50: NOT
.50 is a number!
I have following code that checks whether date is valid. http://jsfiddle.net/uzSU6/36/
If there is blank spaces in date part, month part or year part the date should be considered invalid. For this, currently I am checking the length of string before and after trim operation. It works fine. However is there a better method to check for white spaces? (For example, using === operator)
function isValidDate(s)
{
var bits = s.split('/');
//Javascript month starts at zero
var d = new Date(bits[2], bits[0] - 1, bits[1]);
if ( isNaN( Number(bits[2]) ) )
{
//Year is not valid number
return false;
}
if ( Number(bits[2]) < 1 )
{
//Year should be greater than zero
return false;
}
//If there is unwanted blank space, return false
if ( ( bits[2].length != $.trim(bits[2]).length ) ||
( bits[1].length != $.trim(bits[1]).length ) ||
( bits[0].length != $.trim(bits[0]).length ) )
{
return false;
}
//1. Check whether the year is a Number
//2. Check whether the date parts are eqaul to original date components
//3. Check whether d is valid
return d && ( (d.getMonth() + 1) == bits[0]) && (d.getDate() == Number(bits[1]) );
}
You can use indexOf() function if there is space in the date string.
if(s.indexOf(' ') != -1)
{
//space exists
}
you can test for any whitespace like
if( /\s/g.test(s) )
it will test any whitespace.
You may want to consider using a regexp to test your string's validity:
function isValidDate(s) {
var re = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var mdy = s.match(re);
if (!mdy) {
return false; // string syntax invalid;
}
var d = new Date(mdy[3], mdy[1] - 1, mdy[2]);
return (d.getFullYear() == mdy[3]) &&
(d.getMonth() == mdy[1] - 1) &&
(d.getDate() == mdy[2]);
}
The regex does all this in one go:
checks that there are three fields separated by slashes
requires that the fields be numbers
allows day and month to be 1 or 2 digits, but requires 4 for the year
ensures that nothing else in the string is legal
See http://jsfiddle.net/alnitak/pk4wU/