4

I want users to be able to enter a date format string so they can specify how they want a date value to be displayed/entered.

How can I validate this date format string so that they can enter only a valid Oracle date format strings?

3
  • 3
    Presumably if they enter an invalid format, your code will throw an ORA-01821: date format not recognized error when you try to use it - can't you just pass this back to the calling app? Commented Nov 2, 2011 at 11:40
  • 5
    You also need to consider that there are date formats that are valid but practically useless e.g. 'DD', which would allow the user to enter '12' which would mean the 12th of the current month. I would therefore suggest that you present them with a list of permitted formats to choose from rather than letting them define their own. Commented Nov 2, 2011 at 11:49
  • Thanks, for your suggestions. A list of possible formats is probably the easiest. Commented Nov 2, 2011 at 13:37

1 Answer 1

7

you could create a function:

e.g:

FUNCTION is_valid_date_format ( 
    p_format IN VARCHAR2 ) 
RETURN BOOLEAN IS
    l_date VARCHAR2(100) := NULL;
BEGIN
    l_date := TO_char( sysdate, p_format );
    RETURN TRUE;
EXCEPTION
    WHEN OTHERS THEN
        RETURN FALSE;
END is_valid_date_format;

and use it like this

IF is_valid_date_format('dd/mm/yyyy') THEN

at the moment it will allow time formats too, however it would be simple to extend it to disallow a format that contains undesired formats e.g: hh hh24 mi ss

by adding: (you will probably want to uppercase your format string first)

IF INSTR(p_format,'HH')>0 OR INSTR(p_format,'HH24')>0 
OR INSTR(p_format,'MI')>0  OR INSTR(p_format,'SS')>0 THEN
    RETURN FALSE
END IF;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Kevin but this is not an answer to my question at all. I don't want to know if p_date_as_string matches p_format. I want to know if p_format is a valid format.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.