I need help in forming a regular expression of a date to match YYYYMMDD format. Below are the details:
Input Validation: The value entered is length of 8 and all nu
Example:
^[12][0-9]{3}(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$
Debuggex Demo
WARNING
It's not good idea to use regex for that, since it will pass invalid values like 20140229
, 20140431
, etc. Check @Ben's answer for proper way.
If you want to validate datetime and cannot create functions in Oracle as in @Ben's answer (don't have access/privileges)
Then you can use the following query:
SELECT 'P'
FROM DUAL
WHERE REGEXP_LIKE ('20140229','^[12][0-9]{3}(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$')
AND '20140229' <= TO_CHAR(LAST_DAY(TO_DATE(SUBSTR('20140229', 1, 6) || '01', 'YYYYMMDD')), 'YYYYMMDD');
You do substitute 20140229
with column name.
This is a bad idea. The only way to validate that a date is correct is to attempt to convert it into a date. If the conversion fails then it's not a date; if it's successful then it might be. Dates are far too complex for a regular language to parse.
So, create a function that converts it into a date; you can make if far more generic than you have here, so it can then be reused for other purposes:
create or replace function validate_date (
PDate in varchar2
, PDateFormat in varchar2
) return date is
begin
return to_date(PDate, PDateFormat);
exception when others then
return null;
end;
This returns a date if it's able to validate that the date and date format match, otherwise returns NULL if there's any error. Your query then becomes:
select 'P' from dual where validate_date('20140506', 'yyyymmdd') is not null