Check dateformat with regex in JS - javascript

My question is simple but takes work. I tried lots of regex expressions to check my datetime is ok or not, but though I am sure my regex exprerssion is correct it always return to me isnotok with ALERT. Can you check my code?
validateForLongDateTime('22-03-1981')
function validateForLongDateTime(date){
var regex=new RegExp("/^\d{2}[.-/]\d{2}[.-/]\d{4}$/");
var dateOk=regex.test(date);
if(dateOk){
alert('ok');
}else{
alert('notok');
}
}

There are at least 2 issues with the regex:
It has unescaped forward slashes
The hyphen in the character classes is unescaped and forms a range (matching only . and /) that is not what is necessary here.
The "fixed" regex will look like:
/^\d{2}[.\/-]\d{2}[.\/-]\d{4}$/
See demo
However, you cannot validate dates with it since it will also match 37-67-5734.
Here is an SO post with a comprehensive regex approach that looks viable
Here is my enahanced version with a character class for the delimiter:
^(?:(?:31([\/.-])(?:0?[13578]|1[02]))\1|(?:(?:29|30)([\/.-])(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29([\/.-])0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])([\/.-])(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$
Here is an SO post showing another approach using Date.parse

this way you can validate date between 1 to 31 and month 1 to 12
var regex = /^(0[1-9]|[12][0-9]|3[01])[- \/.](0[1-9]|1[012])[- \/.](19|20)\d\d$/
see this demo here https://regex101.com/r/xP1bD2/1

Related

Javascript regex /^(19|20)([0-9]{2})-([0-9]{2}|0[0-9]{1})-([0-9]{2}|0[0-9]{1})$/g didnt find dates as value of input

and Thanks.
I created a
/^(19|20)([0-9]{2})-([0-9]{2}|0[0-9]{1})-([0-9]{2}|0[0-9]{1})$/g
Pattern in js but didnt work in browser.
I tested Here. Working but in browser js not
Following regex should do the expected check.
\((19|20)\d{2}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))\
You should be able to write your regex as the one below.
(19|20)\d{2}-\d{2}-\d{2}
See this JS code snippet:
var date = ' 2019-04-03 ';
var regex = /(19|20)\d{2}-\d{2}-\d{2}/g;
var result = date.match(regex);
console.log(result[0]);
Depending on what string you are using to match the regex on it could be that using ^ and $ is causing you trouble. Using ^ asserts the position at the start of the line. And using $ asserts the position at the end of the line. This of course means that it won't match if your string is " 1999-01-01 " with spaces or any other text on that same line.
Be advised that if you want it to work for any year and not just 1900 up to 2099 you have to use the one below.
\d{4}-\d{2}-\d{2}
On top of this do note that this captures anything that looks like a date e.g. 2099-99-99 will still be captured but is not a valid date. If you want date validation your regex will look considerably harder, see Regex to validate date format dd/mm/yyyy for an example with leap years and the like. Depending on your use case it might be easier to let Javascript do the validation.
Thats is worked. Thanks.
var date = ' 2019-04-03 ';
var regex = /(19|20)\d{2}-\d{2}-\d{2}/g;
var result = date.match(regex);
console.log(result[0]);

Regex to detect whitespace inside my words

I'm trying to match my timestamp format, but I need to detect whether it is invalid format or not (I need to do something about the invalid format)
Currently, I need to match a space character inside my timestamp:
examples:
[02:21.10,E] or [02:21.10,C#] //correct format
[02:21.10, E] or [10.21.10,E ] //incorrect format, there is a space, but i need to match it with my incorrectRegex
for my correct regex, I use this regex and it is valid:
/\[(\d\d:\d\d\.\d\d),(.*?)\]/g
and for my incorrect regex, I use
/\[\d\d:\d\d\.\d\d,\s*?\]/g
but it didn't find any match for my incorrect format
nb: I'm using a javascript
Try this:
\[\d\d[.:]\d\d[.:]\d\d,(?:[ ][^\]]+?|[^\]]+?[ ])\]
Live Demo.
var re = /\[\d\d[.:]\d\d[.:]\d\d,(?:[ ][^\]]+?|[^\]]+?[ ])\]/;
console.log(re.test('[02:21.10,E]'));;
console.log(re.test('[02:21.10,C#]'));
console.log(re.test('[02:21.10, E]'));
console.log(re.test('[10.21.10,E ]'));
console.log(re.test('[10.21.10,C# ]'));
console.log(re.test('[02:54.97,C#]single[02:55.61,A ]'));
PS: I assume it is not an error that your second invalid sample [10.21.10,E ] does not contain a : after the first two digits. I have applied the same for the second dot/colon.

date validation regex - make leading zeroes optional

I currently use the following regex from http://regexlib.com to validate the incoming date using the pattern YYYY-MM-DD. But the leading zeroes are mandatory and I want it to be optional.
((((1[26]|2[048])00)|[12]\d([2468][048]|[13579][26]|0[48]))-((((0[13578]|1[02])-(0[1-9]|[12]\d|3[01]))|((0[469]|11)-(0[1-9]|[12]\d|30)))|(02-(0[1-9]|[12]\d))))|((([12]\d([02468][1235679]|[13579][01345789]))|((1[1345789]|2[1235679])00))-((((0[13578]|1[02])-(0[1-9]|[12]\d|3[01]))|((0[469]|11)-(0[1-9]|[12]\d|30)))|(02-(0[1-9]|1\d|2[0-8]))))
Debuggex Demo
Test case
2000-01-01
2000-1-1
2000-01-1
2000-1-01
are all valid. But only the first test case is accepted, as of now.
Can you please help?
You can achieve this much more simply using a function rather than a regular expression. The following is much simpler to understand and therefore maintain (though it shouldn't ever need any), and is a lot less code that the regular expression in the OP.
function isValidISODate(s) {
var b = s.split(/\D/);
var d = new Date(b[0],--b[1],b[2]);
return d && d.getMonth() == b[1];
}
// Some tests
['2016-1-1','2016-01-01','2016-2-29','2016-02-30'].forEach(
s=>console.log(s + ': ' + isValidISODate(s))
);
You can make a number optional by adding them the number of permitted ocurrences {0,1}. That is {1,2} to accept either 1 character or 2.
A simple version:
[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}
Edit: Your version is easy to "fix". Simply add {0,1} after the compulsory 0:
// Before.
((((0[13578]
// After.
((((0{0,1}[13578]
Edit2: As #Toto has said {0,1} is the same as ?
((((0?[13578]
Using this regex - '\d+-[0-2]* [0-9]-[0-3]* [0-9]' may help .

Regex for date in format hour.minute dayName day/month

I am trying to verify str with the code below. My final goal is to allow this style of input:
18.30 Saturday_lastMatch 3/10
However, the code I have can't even work for the basic usage (98.5% str will be of this format):
19.30 Friday 15/5
var regex= /[0-9]{2}[\.:][0-9]{2} [A-Z][a-z]{4,7} [0-9]\/[0-9]{2}/;
if(!str.match(regex)) {
//"Bad format, match creation failed!");
}
What am I missing?
There are a number of problems with your regex.
The date & time matching portions at the beginning and end don't allow for 1 or 2 digit numbers as they should.
You may want to consider anchoring the regex at the beginning and end with ^ and $, respectively.
The literal dot in the character class doesn't need to be escaped.
Try this:
var regex= /^[0-9]{1,2}[.:][0-9]{1,2} [A-Z][a-z]{5,8} [0-9]{1,2}\/[0-9]{1,2}$/;
The final part of your regular expression that checks day/month needs to be expanded. It currently only matches #/##, but it should allow ##/# as well. The simplest fix would be to allow either one or two digits on either side (e.g. 12/31)
var regex= /[0-9]{2}[\.:][0-9]{2} [A-Z][a-z]{4,7} [0-9]{1,2}\/[0-9]{1,2}/;

Javascript UK Postcode Validation [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
UK Postcode Regex (Comprehensive)
I have the following code for validating postcodes in javascript:
function valid_postcode(postcode) {
postcode = postcode.replace(/\s/g, "");
var regex = /[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}/i;
return regex.test(postcode);
}
Tests:
CF47 0HW - Passes - Correct
CF47 OHW - Passes - Incorrect
I have done a ton of research but can't seem to find the definitive regex for this common validation requirement. Could someone point me in the right direction please?
Make your regex stricter by adding ^ and $. This should work:
function valid_postcode(postcode) {
postcode = postcode.replace(/\s/g, "");
var regex = /^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
return regex.test(postcode);
}
You want a 'definitive regex' - given all the permutations of the UK postcodes, it needs to be therefore 'unnecessarily large'. Here's one I've used in the past
"(GIR 0AA)|((([ABCDEFGHIJKLMNOPRSTUWYZ][0-9][0-9]?)|(([ABCDEFGHIJKLMNOPRSTUWYZ][ABCDEFGHKLMNOPQRSTUVWXY][0-9][0-9]?)|(([ABCDEFGHIJKLMNOPRSTUWYZ][0-9][ABCDEFGHJKSTUW])|([ABCDEFGHIJKLMNOPRSTUWYZ][ABCDEFGHKLMNOPQRSTUVWXY][0-9][ABEHMNPRVWXY])))) [0-9][ABDEFGHJLNPQRSTUWXYZ]{2})"
Notice I never just use A-Z, for instance, because in each part there are always certain letters excluded.
The problem is the first line of your function. By trimming the spaces out of the target string, you allow false positives.
CF47OHW will match [A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}
CF matches [A-Z]
4 matches [0-9]{1,2}
(blank) matches \s?
7 matches [0-9]
OH matches [A-Z]{2}
W gets discarded
So, as Paulgrav has stated, adding the start and end characters (^ and $) will fix it.
At that point, you can also remove the \s? bit from the middle of your regex.
However! Despite the bug being fixed, your regex is still not going to work how you'd like it to. You should look at the following rather good answer on this here site UK Postcode Regex (Comprehensive)

Categories