I've just written this regular expression in javaScript however it doesn't seem to work, here's my function:
function isGoodDate(dt){
var reGoodDate = new RegExp("/^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$/");
return reGoodDate.test(dt);
}
and this is how I call it in my form validation
if(!isGoodDate(userInput[1].value)){
alert("date not in correct format of MM/dd/YYYY");
return false;
}
now I want it to return MM/DD/YYYY however if I put a valid date in it raises the alert? Any ideas anyone?
Attention, before you copy+paste: The question contains some syntactic errors in its regex. This answer is correcting the syntax. It is not claiming to be the best regex for date/time parsing.
Try this:
function isGoodDate(dt){
var reGoodDate = /^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$/;
return reGoodDate.test(dt);
}
You either declare a regular expression with:
new RegExp("^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$")
Or:
/^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$/
Notice the /
Maybe because you are declaring the isGoodDate() function, and then you are calling the isCorrectDate() function?
Try:
function isGoodDate(dt){
var reGoodDate = /^(?:(0[1-9]|1[012])[\/.](0[1-9]|[12][0-9]|3[01])[\/.](19|20)[0-9]{2})$/;
return reGoodDate.test(dt);
}
Works like a charm, test it here.
Notice, this regex will validate dates from 01/01/1900 through 31/12/2099. If you want to change the year boundaries, change these numbers (19|20) on the last regex block. E.g. If you want the year ranges to be from 01/01/1800 through 31/12/2099, just change it to (18|20).
I agree with #KooiInc, but it is not enough to test for NaN
function isGoodDate(dt){
var dts = dt.split('/').reverse()
,dateTest = new Date(dts.join('/'));
return !isNaN(dateTest) &&
dateTest.getFullYear()===parseInt(dts[0],10) &&
dateTest.getMonth()===(parseInt(dts[1],10)-1) &&
dateTest.getDate()===parseInt(dts[2],10)
}
which will handle 29/2/2001 and 31/4/2011
For this script to handle US dates do
function isGoodDate(dt){
var dts = dt.split('/')
,dateTest = new Date(dt);
return !isNaN(dateTest) &&
dateTest.getFullYear()===parseInt(dts[2],10) &&
dateTest.getMonth()===(parseInt(dts[0],10)-1) &&
dateTest.getDate()===parseInt(dts[1],10)
}
Add this in your code, it working perfectly fine it here.
click here http://jsfiddle.net/Shef/5Sfq6/
function isGoodDate(dt){
var reGoodDate = /^(?:(0[1-9]|1[012])[\/.](0[1-9]|[12][0-9]|3[01])[\/.](19|20)[0-9]{2})$/;
return reGoodDate.test(dt);
}
I don't think you need a regular expression for this. Try this:
function isGoodDate(dt){
var dts = dt.split('/').reverse()
,dateTest = new Date(dts.join('/'));
return isNaN(dateTest) ? false : true;
}
//explained
var dts = dt.split('/').reverse()
// ^ split input and reverse the result
// ('01/11/2010' becomes [2010,11,01]
// this way you can make a 'universal'
// datestring out of it
,dateTest = new Date(dts.join('/'));
// ^ try converting to a date from the
// array just produced, joined by '/'
return isNaN(dateTest) ? false : true;
// ^ if the date is invalid, it returns NaN
// so, if that's the case, return false
Validate (DD-MM-YYYY) format :)
function isGoodDate(dt) {
var reGoodDate = /^(?:(0[1-9]|[12][0-9]|3[01])[\-.](0[1-9]|1[012])[\-.](19|20)[0-9]{2})$/;
return reGoodDate.test(dt);
}
Try the below code which accepts following date formats:
MM-DD-YYYY, MM-DD-YY, DD-MM-YYYY, DD-MM-YY, MM/DD/YYYY, MM/DD/YY,
DD/MM/YYYY, DD/MM/YY, MM\DD\YYYY, MM\DD\YY, DD\MM\YYYY, DD\MM\YY
function isGoodDate(dt) {
var reGoodDate = /(?:((0\d|[12]\d|3[01])|(0\d|1[012]))[\-|\\|\/]((0\d|1[012])|(0\d|[12]\d|3[01]))[\-|\\|\/](((19|20)\d{2})|\d\d))/;
return reGoodDate.test(dt);
}
(/^(0[1-9]|1[012])- /.- /.\d\d$/)
You can use this will work definitely and this is for MM/DD/YYYY
Related
I need to convert a formatted number to JS default number format.
This is my code:
String.prototype.toJsFloatFormat = function() {
debugger;
var newVal = this;
return newVal;
}
//Example of use
var input = 10000.22; //default js format
var formatted = input.toLocaleString("es"); // result is: 10.000,22
var unformatted = formatted.toJsFloatFormat(); //expected result = 10000.22;
The problem is when I need to get the formatted number (10.000,22) and I make operations with this formatted number (parseFloat(10.000,22) + 1000) I have bad results ( parseFloat(10.000,22) + 1000 = 1010)
thanks in advance.
It's not easy. There's a reason why most of the comments have said "Don't try -
do your calculations on the number itself, not the formatted value".
You need to work out what the decimal and thousand separator characters are. For that, you will need to know which locale the number was converted into.
(1234.5).toLocaleString("es").match(/(\D+)/g);
// -> [".", ","]
Once you have that, you can replace characters in the formatted string.
function unformatString(string, locale) {
var parts = (1234.5).toLocaleString(locale).match(/(\D+)/g);
var unformatted = string;
unformatted = unformatted.split(parts[0]).join("");
unformatted = unformatted.split(parts[1]).join(".");
return parseFloat(unformatted);
}
There is no way of working out the locale - you have to know it and pass it to the function.
no need to reinvent the wheel -
https://github.com/globalizejs/globalize#readme
var input = 10000.22;
Globalize.parseFloat(input );
I did it this way(in my case it was the 'ru' local format, so I did replace the 'space' symbol):
var myNumber = 1000000;
var formated = myNumber.toLocaleString('ru');
var unformated = parseInt(formated.replace(/\s/g, ''));
your case:
var formated = myNumber.toLocaleString('en');
var unformated = parseInt(formated.replace(/,/g, ''));
I did this, that's fine for me
function localeStringToFloat(locale){
if(!locale) return locale
let test=1000
test=test.toLocaleString(undefined,{minimumFractionDigits: 2,maximumFractionDigits: 2});
let separator=test[1]
let decimalSeparator=test[5]
return parseFloat(locale.replaceAll(separator,'').replace(decimalSeparator,'.'))
}
My functions for format and unFormat currency numbers to 'en-US'. I hope helps
function myFormatPrice(num,digits){
return num.toLocaleString('en-US', {maximumFractionDigits:digits});
}
function myUnFormatPrice(formated){
return parseFloat( formated.replaceAll(',','') );
}
I've tested the three of the regex's on http://www.regexpal.com/ and they are what I need, but when doing a regex test 2 of them return false (BTC and CAD) and only the Bitcoin address seems to work (you may test with this wallet below).
13dHNxtbckAFM4PzdBqWgymFJmcv3Yzi32
https://jsfiddle.net/ps2fj1ff/1
(all the relevant code is in the html section)
var regWallet = new RegExp("^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$");
var regBTC = new RegExp("^\d*\.\d*$");
var regCAD = new RegExp("^\d+(\.(\d{2}))?$");
$('#button1').on('click', function() {
var btcCheck = $('#amount_btc').val();
if (regBTC.test(btcCheck)) {
} else {
alert("Invalid BTC value!");
}
var cadCheck = $('#amount_cad').val();
if (regCAD.test(cadCheck)) {
} else {
alert("Invalid CAD value!");
}
var walletCheck = $('#wallet').val();
if (regWallet.test(walletCheck)) {
} else {
alert("Invalid Bitcoin address, please make sure you've entered a valid address!");
}
});
The reason is that in var regBTC = new RegExp("^\d*\.\d*$"); the \ is used to escape the character so if you console.log(regBTC) you will see it as ^d*.d*$.
To prevent this you will have to double escape it: var regBTC = new RegExp("^\\d*\\.\\d*$");
Or better yet use / instead: var regBTC = /^\d*\.\d*$/;
The same goes for the other regex too.
(I initially thought single quote would work too, but apparently not in javascript)
Use this instead:
var regBTC = /^\d*\.\d*$/;
var regCAD = /^\d+(\.(\d{2}))$/;
It's cleaner and more readable as most editors will give you regexp syntax highlighting in this format.
There really isn't any good reason to use new RegExp which forces you to write the expression as a string, which forces you to use confusing escapes, when there is a proper regular expression syntax built into JavaScript.
Im trying to implement a validation for an input field in IBM BPM.
Im not really familiar with java script but I try to get method that returns
ture if a string contains any numbers.
awdadw = valid
awdawd2d = invalid
I tried this method:
function hasNumbers(t)
{
var pattern=new RegExp("^[A-Za-z]+$");
return pattern.test(t); // true if string. Returns false for numbers
}
When I try this function, it says that method / variable RegExp is unknown. Since it is rather basci stuff I hope to get some sources where this topic is explained.
You can use this:
function validate(){
var re = /^[A-Za-z]+$/;
if(re.test(document.getElementById("inputID").value))
alert('Valid Name.');
else
alert('Invalid Name.');
}
Based on adre3wap this worked for me:
function validate(t){
var re = /^[A-Za-z]+$/;
if(re.test(t))
return false;
else
return true;
}
I am new to javascript. I am fixing bug programmed by others. I see validation code in javascript as:
function validateTime(str) {
var pattern = new RegExp(/^(([0-9])|([0-1][0-9])|([2][0-3])):(([0-9])|([0-5][0-9]))$/);
if (pattern.test(str)) {
return true;
}
else {
return false;
}
}
But it does't validate time:- 22-05-2015
How can it be done?
You can use the Date object's parse method to verify a date string.
You can then check if the value of Date.parse(str) is equal to "Invalid Date" to see if it is malformed. No need for regex at all.
Your regex validates time, not date. To check against date in your format, use this:
var pattern = new RegExp(/^(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[012])-(19|20)\d\d$/);
You can check this pattern here:
https://regex101.com/r/kB5nV2/1
function parseDate(str) {
var m = str.match(/^(\d{1,2})-(\d{1,2})-(\d{4})$/);
return (m) ? new Date(m[3], m[2]-1, m[1]) : null;
}
The function validateTime(str) used in your code is for time validation. Try the parseDate(str) for date validation.
I am developing a application. In this application have a input field. where the user can input the dates by different formats like
ddmmyy, ddmmyyyy, dd-mm-yy, mm-dd-yy
And I need to verify the date whether that valid or not. I can able to validate this way:
YYYY-MM-DD using:
var myDate = new Date("1987-08-06") // it returns me the date while this valid.
But I can't able to validate with other formats. how can i validate that?
example:
var myDate = new Date("08-06-1987")..etc?
I developed my app using jQuery. I am looking some solution without using a plug-in. since i used no.of plugins already.
thanks in advance!
I would do it with regular expressions. You could define a regexp pattern for each of your formats. Then you can test if the String from the input field matches any of the pattern.
Somthing like this:
var regExpDDMMYY = /[0-9]{2}[0-1][0-9][0-9]{2}/g;
var regExpddmmyyyy = ...;
...
...
if (regExpDDMMYY.test(yourInputStringFromDateField)) {
// handleDateAs DDMMYY
} else if (regExpddmmyyyy .test(yourInputStringFromDateField)) {
...
} else {
throw new YourException();
}
You can find an example here:
http://www.w3schools.com/js/js_regexp.asp
Unfortunately, there's no "parseExact" in native JS, that would also be crossbrowser. So you either need to use Date.js library or write some converter.
For this task i'd recommend you to use "Chain of responsibility" pattern
function DateTimeParser() {
this.parse = function (input) {
for (var key in Parsers) {
var result = Parsers[key].parse(input);
if (result !== null)
return result;
}
return null;
};
this.parseExact = function (input, format) {
var parser = Parsers[format];
return parser ? parser.parse(input) : null;
};
var ConcreteDateTimeParser = function (expression, parser) {
this.parse = function (input) {
if (!input.match(expression))
return null;
var result = parser(input);
return isNaN(result.getDate()) ? null : result;
};
};
var Parsers = {
"dd-mm-yyyy": new ConcreteDateTimeParser(/\d{2}\-\d{2}\-\d{4}/, function (input) {
var dd = parseInt(input.slice(0, 2)),
mm = parseInt(input.slice(3, 5)),
yyyy = parseInt(input.slice(-4));
return new Date(yyyy, mm, dd);
}),
"ddmmyyyy": new ConcreteDateTimeParser(/\d{8}/, function (input) {
var dd = parseInt(input.slice(0, 2)),
mm = parseInt(input.slice(2, 4)),
yyyy = parseInt(input.slice(-4));
return new Date(yyyy, mm, dd);
})
};
};
var instance = new DateTimeParser();
instance.parse('22122012');
instance.parseExact('22122012', 'ddmmyyyy');
instance.parseExact('22122012', 'dd-mm-yyyy'); // null
From this you can extend your Parsers lib with additional parsers. You also can use different sets of parsers by passing them into DateTimeParser as a constructor argument. My code is pretty trivial, for i didn't want to write it mega-deep, just wanted to show the way =)