Javascript RegExp to only allow certain characters at certain places
I want to use a regexp to "force" a user to correctly format a timestamp.
At the moment I can restrict input so that the user can only input numbers, a dash, or a colon using the following:
function allownumbers(e) {
var key = window.event ? e.keyCode : e.which;
var keychar = String.fromCharCode(key);
var reg = new RegExp("[-0-9: ]")
if (key == 8) {
keychar 开发者_如何学运维= String.fromCharCode(key);
}
if (key == 13) {
key = 8;
keychar = String.fromCharCode(key);
}
return reg.test(keychar);
}
However, the user could still enter invalid data, e.g. 0000::--12354 would validate.
Can I use a regexp to force the user to enter ####-##-## ##:##:## (e.g. 2010-12-15 10:57:01)?
(Even cooler would be if it automatically added the dashes, colons and space when it hit the correct place in the string.)
Cheers,
Ben
Use the jQuery validation plugin.
Since you have a custom date format, I'll point you to this SO post.
If you want to force a certain pattern during input, look no further than masked input plugin.
Your regexp pattern can be
var re = /\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d/;
You can do this easily - just use {} to limit the number of entries. As a fairly crude example, regex: [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}
will do what you want, just test it against the whole content of the textbox - e.g. reg.match(e.srcElement.value).
If you want it to be testing as you go along, you can use the code from this site to determine the cursor position, and then check the new input against what you are expecting at that position, and yes, even add in the dash or space automatically.
Why not just use a small block of validation? after they've entered the string...
var date = new Date(dtStr);
if (isNaN(date) && dtStr != "MM/DD/YYYY") {
return alert('Please enter a valid date');
}
else {
if (date.getFullYear() > 2100 || date.getFullYear() < 1900) {
return alert("Please enter a valid year");
}
}
精彩评论