L
libsfan01
how can i use regular expressions to ensure a mysql format date entry
in a text field?
thanks
marc
in a text field?
thanks
marc
libsfan01 said:how can i use regular expressions to ensure a mysql format date entry
in a text field?
libsfan01 said:how can i use regular expressions to ensure a mysql format date entry
in a text field?
libsfan01 said:how can i use regular expressions to ensure a mysql format date entry
in a text field?
I suppose you don't need years Ante Christum Natum or above 9999, which
aren't supported by MySQL's DATE type field. Please note that one- or
two-digit year notations are treated specially in MySQL
(0-69=>2000-2069 and 70-99=>1970-1999. Just use four digits to play
safe, eg 0006=>0006).
Note that the DATE field type in MySQL accepts Y(Y)(Y)(Y)-M(M)-D(D),
but doesn't actually check whether the date really exists up to day 31
(e.g. dates like 2006-2-31 are accepted).
Strictly the hyphens aren't even necessary, but I would counsel to keep
them in order to avoid all kinds of ambiguous situations.
Once you're aware of the above:
var D = '1941-8-19';
var S = D.split('-');
if ( /^\d{1,4}$/.test(S[0])
&& /^\d{1,2}$/.test(S[1])
&& 0 < parseFloat(S[1])
&& parseFloat(S[1]) < 13
&& /^\d{1,2}$/.test(S[2])
&& 0 < parseFloat(S[2])
&& parseFloat(S[2]) < 32
)
alert('date is OK to insert in MySQL');
Hope this helps,
doing it with regexp only and checking for Valid dates no 2006-2-29:
doing it with regexp only and checking for Valid dates no 2006-2-29:
RobG said:Just about everything you ever needed to know about date validation is
here:
<URL: http://www.merlyn.demon.co.uk/js-date4.htm >
The trivial way that checks the format only, not validity, is:
var dateString = '2006-2-31';
alert( /\d{4}-\d\d?-\d\d?/.test(dateString)); // Shows true
For validation, a simple way is to convert the incoming date string to
a date object then test if the generated date matches the string - you
only need to test 2 of the 3 bits:
var dateString = '2006-02-31';
alert( /\d{4}-\d{2}-\d{2}/.test(dateString));
var dateBits = dateString.split('-');
var dateObj = new Date(dateString.replace(/-/g,'/'));
var isValid = ( dateBits[0] == dateObj.getFullYear()
&& dateBits[1] == (dateObj.getMonth()+1));
alert(isValid); // Shows false.
news:comp.lang.javascript said:For validation, a simple way is to convert the incoming date string to
a date object then test if the generated date matches the string - you
only need to test 2 of the 3 bits:
var dateString = '2006-02-31';
alert( /\d{4}-\d{2}-\d{2}/.test(dateString));
var dateBits = dateString.split('-');
var dateObj = new Date(dateString.replace(/-/g,'/'));
var isValid = ( dateBits[0] == dateObj.getFullYear()
&& dateBits[1] == (dateObj.getMonth()+1));
alert(isValid); // Shows false.
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.