I want to create a html form with a text-field which checks if DD-MM-YYYY are correctly entered into the field and alerts the user if it's not the case. How can i approach this with javascript?
3 Answers
Couldn't you just make 3 <input> fields - one for month, day, and year?
3 Comments
jan
i think that's possible as well, but how do i name the seperate input fields so it all can be stored in one field in my db?
In JS, after the user key's off or hits enter, you could test the value (assuming the <input> has an id of inpdate for sake of example):
var val = document.getElementById('inpdate').value;
var check = /^\s*\d{2}-\d{2}-\d{4}\s*$/;
if(check.test(val)){
// it's good
}
else {
// not valid
}
I put \s* in to allow leading and trailing whitespace. Up to you if you would want to allow that.
Comments
JS Fiddle
Went a little overboard (and it's still not robust), but it allows you to change the format (MM-DD-YYYY) to something else like (YYYYMMDD).
HTML
<input type="text" name="date" id="date-input" onkeyup="checkDate.call(this)" />
<pre id="debug"></pre>
JS
var debug = document.getElementById('debug');
var checkDate = function(){
var format = 'MM-DD-YYYY';
var delim = '-';
var inputs = { object : this
, day : { order : undefined
, length : undefined
, value : undefined
}
, month : { order : undefined
, length : undefined
, value : undefined
}
, year : { order : undefined
, length : undefined
, value : undefined
}
};
// Decipher Format Positioning
var temp = ['Y','M','D'];
var pos = [];
for (var i=0,n=temp.length; i<n; i++){
pos[i] = [];
pos[i].push(format.indexOf(temp[i])); // start
pos[i].push(temp[i]); // letter
pos[i].push(format.lastIndexOf(temp[i])-pos[i][0]); // length
}
pos.sort();
// Store the positions
for (var i=0,n=pos.length; i<n; i++){
switch (pos[i][1]){
case 'D': inputs.day.order =i; inputs.day.length =pos[i][2]; break;
case 'M': inputs.month.order =i; inputs.month.length =pos[i][2]; break;
case 'Y': inputs.year.order =i; inputs.year.length =pos[i][2]; break;
}
}
// Build Regex
//alert(format);
var temp = format.split(/[^a-zA-Z]/);
var regex = '';
for(var i=0,n=temp.length; i<n; i++){
regex += '(\\d{' + temp[i].length + '})';
}
var re = new RegExp(regex);
var matches = re.exec(inputs.object.value.replace(/[^0-9]/g,''));
if (matches && matches.length>0){
inputs.day.value = matches[inputs.day.order +1];
inputs.month.value = matches[inputs.month.order +1];
inputs.year.value = matches[inputs.year.order +1];
debug.innerHTML = 'Valid Date: \n'
+ '\tDay: ' + inputs.day.value + '\n'
+ '\tMonth: ' + inputs.month.value + '\n'
+ '\tYear: ' + inputs.year.value + '\n';
} else {
debug.innerHTML = 'Not a valid date!';
}
};
9999okay? How about day45?<input type="date">in Webkit browsers. Also, pretty good plugin: masked input