views:

96

answers:

2

Hi,

Is there any way I can easily check if a string conforms to the SortableDateTimePattern ("s"), or do I need to write a regular expression?

I've got a form where users can input a copyright date (as a string), and these are the allowed formats:

Year: YYYY (eg 1997)

Year and month: YYYY-MM (eg 1997-07)

Complete date: YYYY-MM-DD (eg 1997-07-16)

Complete date plus hours and minutes: YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)

Complete date plus hours, minutes and seconds: YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)

Complete date plus hours, minutes, seconds and a decimal fraction of a second YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)

I don't have much experience of writing regular expressions so if there's an easier way of doing it I'd be very grateful!

A: 

I'd split the input field into many (one for year, month, day etc.).

You can use Javscript to advance from one field to the next once full (i.e. once four characters are in the year box, move focus to month) for smoother entry.

You can then validate each field independently and finally construct the complete date string.

Kris
They don't have to fill in the full date though, it's perfectly valid for them to just give the year. So I want an open string so they're free to input the date in either of the formats above.
swedeheart
I got that, you wouldn't require anything but the year be filled out. Expecting users to know the formats you specify above is very questionable. I'd only accept it as a requirement if the user group was both technically minded and would be using the tool alot and could be expected to learn this convention.
Kris
I see what you mean, at the moment this is an internal tool only so the users will be aware of what they need to put in, but it might become external and in that case I'll take your suggestion into consideration. Thanks!
swedeheart
+1  A: 

Not thoroughly tested and hence not foolproof, but the following seems to work:

var regex:RegExp = /(?<=\s|^)\d{4}(-\d{2}(-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d{2})?)?\+\d{2}:\d{2})?)?)?(?=\s|$)/g;
var test:String = "23 1997 1998-07 1995-07s 1937-04-16 " + 
                  "1970-0716 1993-07-16T19:20+01:01 1979-07-16T19:20+0100 " + 
                  "2997-07-16T19:20:30+01:08 3997-07-16T19:20:30.45+01:00";
var result:Object
while(result = regex.exec(test))
    trace(result[0]);

Traced output:

1997
1998-07
1937-04-16
1993-07-16T19:20+01:01
2997-07-16T19:20:30+01:08
3997-07-16T19:20:30.45+01:00

I am using ActionScript here, but the regex should work in most flavors. When implementing it in your language, note that the first and last / are delimiters and the last g stands for global.

Amarghosh
Brilliant, this seems to work fine! Thanks!
swedeheart