checking date on the basis of multiple format - javascript

I have written below lines of code for checking date format on the basis of multiple date formats like
function checkValidDate(dateValue)
{
var dateFormat = getDateFormat();
switch(dateFormat)
{
case "d-m-Y":
var regex = /^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/;
if(dateValue.match(regex))
return true;
else
return false;
break;
case "m-d-Y":
var regex = /^(0[1-9]|1[012])[-/.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$/;
if(dateValue.match(regex))
return true;
else
return false;
break;
case "Y-m-d":
var regex = /^(19|20)\d[- /.](0[1-9]|1[012]\d(0[1-9]|[12][0-9]|3[01]))$/;
if(dateValue.match(regex))
return true;
else
return false;
break;
}
}
$("#dobfield").blur(function(){
var dob = $("#dobfield").val().trim();
var check = checkValidDate(dob);
if(check ==false)
alert("wrong");
});
There are three formats accepted in this project "d-m-Y", "m-d-Y", "Y-m-d".
Now I am trying to check whether the date entered is in valid regular expression format or not on the basis of presently selected date format.
The above code is not working!!! Please help me!!!

function checkValidDate(dateValue)
{
var dateFormat="d-m-Y";
switch(dateFormat)
{
case "d-m-Y":
var regex = /^([1-9]|[12][0-9]|3[01])[- /.]([1-9]|1[012])[- /.]\d\d$/;
if(dateValue.match(regex))
return true;
else
return false;
break;
case "m-d-Y":
var regex = /^([1-9]|1[012])[- /.]([1-9]|[12][0-9]|3[01])[- /.]\d\d$/;
if(dateValue.match(regex))
return true;
else
return false;
break;
case "Y-m-d":
var regex = /^\d\d[- /.]([1-9]|[12][0-9]|3[01])[- /.]([1-9]|1[012])$/;
if(dateValue.match(regex))
return true;
else
return false;
break;
default:
return false;
break;
}
}
I have changed the regex little bit to support the format that you have told. Hope this help you.
Working Example

I see multiple problems here.
In amount of code provided - not self testable example
At definition - what is d-m-Y?
Possibly at regex, depending on former point.
But the biggest problem is in approach.
Does switch using dateFormat work?
Is d-m-Y in fact dd-mm-YYYY?
In that case, 1st regex (didn't test beyond that - no point) is wrong. This one will work:
case "d-m-Y":
var regex = /^(0?[1-9]|[12][0-9]|3[01])[\-\-](0?[1-9]|1[012])[\-\-]\d{4}$/;
Using regex for this is not enough. You gonna need way more complex regex to filter out dates like 31-2-year, or years that have or not have 29-2 for example.
Your best bet is to use MomentJS. It's simple, not lightweight and battle-tested with good documentation.

Related

RegEx test method returns false when it should be true

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.

Javascript method to check for digits within a string (validation of input data)

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;
}

DateTime Validation in javascript

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.

Manually parsing JSON before parsing to object

I'm creating a DSL based on JSON and JavaScript and I have a requirement to let key values be specified 'raw' and not enclosed in string delimiters. A quick example that hopefully explains this:
{myKey:custom_function('arg1'), myKey2:custom_function("another arg1")}
should become
{myKey:"custom_function('arg1')", myKey2:"custom_function(\"another arg1\")"}
This is because at the time of parsing the JSON object, custom_function will not exist. I need to be able to parse the JSON without evaluating any of the values, then only expand values one by one as I iterate the keys.
What regular expression or other method can I use to turn that 1st snippet into the 2nd one?
I'm assuming a simpler solution will cover 90% of cases but that writing a bullet-proof implementation would take a lot of effort. Based on the research I did into JavaScript's regular expression support (apparantly no lookbehind capability) I'm assuming it will require something more than just 1 or 2 lines of regex patterns.
Also, this is for a node application so any tricks that it has for this will be helpful too.
EDIT:
This question seems to be getting some downvotes, but I've left it up anyway for the benefit of future googlers / my own reference. It's a perfectly valid question about what method / technique would work best for this kind of problem, and there could easily be other node/js newcomers who face a similar problem.
Final answer: Regex just isn't suited to a task as complex as this. Any similarly complex solutions I found online (e.g. removing code comments) all resorted to a mainly custom, iterative approach, only using regex sparingly, so a similar approach ended up being not too painless in this situation.
So in the end the 'best' method I could find didn't involve very much regex or any specialized libraries from node or elsewhere suited to the problem.
Finally, for the benefit of future googlers who might have a similar problem, I've published my solution at https://gist.github.com/2590689 and copied below:
//clothe a hub file that has 'naked' expressions
//e.g. turn {key:$('body p')} into {key:"$('body p')"}
function clothe(contents){
closers = /[\}\]\)\/"']/
openers = /[\{\[\(\/"']/
closing = {
"{": "}",
"[": "]",
"(": ")",
"/": "/",
'"': '"',
"'": "'"
}
contents = contents.split("");
var beforeKey = true;
var inKey = false;
var beforeValue = false;
var inValue = false;
var inArray = false;
var delimiterStack = [];
function inDelimited(){
return delimiterStack.length > 0;
}
function toggleDelimiter(d){
if(openers.exec(d) && !closers.exec(d)){
pushDelimiter(d);
}else if(openers.exec(d) && closers.exec(d)){
if(topDelimiter()){
if(topDelimiter()==d){
popDelimiterIfValid(d);
}else{
pushDelimiter(d);
}
}else{
pushDelimiter(d);
}
}else if(closers.exec(d)){
popDelimiterIfValid(d);
}
}
function topDelimiter(){
if(delimiterStack.length>=0){
return delimiterStack[delimiterStack.length-1];
}else{
return undefined;
}
}
function pushDelimiter(d){
delimiterStack.push(d);
}
function popDelimiterIfValid(d){
if(delimiterStack.length>0)
if(closing[delimiterStack[delimiterStack.length-1]]==d)
delimiterStack.pop(d);
}
function rTrimmedRightBound(rightBound){
while(rightBound>0){
if(!/\s/g.exec(contents[--rightBound])){
return rightBound+1;
}
}
}
for(var i=0; i<contents.length; i++){
function delimiterCheck(c){
if(c=='"'){
toggleDelimiter('"');
contents.splice(i, 0, '\\');
i++;
}else if(openers.exec(c) || closers.exec(c)){
toggleDelimiter(c)
}
}
if(beforeKey){
if(/[a-zA-Z0-9$_!]/.exec(contents[i])){
beforeKey = false;
inKey = true;
}
}else if(inKey){
if(contents[i]==":"){
inKey = false;
beforeValue = true;
}
}else if(beforeValue){
if(/[a-zA-Z0-9$_!'"\(\/]/.exec(contents[i])){
contents.splice(i, 0, '"');
i++;
beforeValue = false;
inValue = true;
delimiterCheck(contents[i]);
}else if(/\{/.exec(contents[i])){
beforeKey = true;
beforeValue = false;
}else if(/\[/.exec(contents[i])){
beforeValue = false;
inArray = true;
}
}else if(inArray && !inValue){
if(/[a-zA-Z0-9$_!'"\(\/]/.exec(contents[i])){
contents.splice(i, 0, '"');
i++;
beforeValue = false;
inValue = true;
delimiterCheck(contents[i]);
}
}else if(inValue){
if(!inDelimited() && /[\},\]]/.exec(contents[i])){
contents.splice(rTrimmedRightBound(i), 0, '"');
i++;
inValue = false;
if(/\]/.exec(contents[i])){
inArray = false;
}
beforeKey = !inArray;
}else{
delimiterCheck(contents[i]);
}
}
}
return contents.join("");
}

Regular Expression for MM/DD/YYYY in Javascript

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

Categories