Regular Expression of a specific Date format

前端 未结 2 1145
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-15 17:18

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

2条回答
  •  青春惊慌失措
    2021-01-15 17:56

    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
    

提交回复
热议问题