Reputation: 1368
I have a question. How would I be able to validate or format a location number 00-00-00-000-000 digits 0-9 where 0 is via java-script.
something like this
function formatTime(time) {
var result = false, m;
var re = /^\s*([01]?\d|2[0-3]):?([0-5]\d)\s*$/;
if ((m = time.match(re))) {
result = (m[1].length == 2 ? "" : "0") + m[1] + ":" + m[2];
}
return result;
}
alert(formatTime(" 1:00"));
alert(formatTime("1:00 "));
alert(formatTime("1:00"));
alert(formatTime("2100"));
alert(formatTime("90:00")); // false
Upvotes: 0
Views: 295
Reputation: 18076
Simple function: JSFiddle
works for any input string that is in the format X-X-X-X-X
where the first three Xs can be between 0 and 99 and the last 2 Xs can be between 0 and 999.
function doIt(lala) {
var reg = /^\s*([0-9]{1,2})\-([0-9]{1,2})\-([0-9]{1,2})\-([0-9]{1,3})\-([0-9]{1,3})\s*$/;
var m = lala.match(reg);
if(m) {
var n1 = m[1].length == 1 ? ('0' + m[1]) : m[1];
var n2 = m[2].length == 1 ? ('0' + m[2]) : m[2];
var n3 = m[3].length == 1 ? ('0' + m[3]) : m[3];
var n4 = m[4].length == 1 ? ('00' + m[4]) : (m[4].length == 2 ? '0' + m[4] : m[4]);
var n5 = m[5].length == 1 ? ('00' + m[5]) : (m[5].length == 2 ? '0' + m[5] : m[5]);
return (n1 + '-' + n2 + '-' + n3 + '-' + n4 + '-' + n5);
}
return ''; // you can choose to return false here
// if you want to use this as some sort of validation
}
Upvotes: 1