Annie Alan Annie Alan - 7 months ago 13
Javascript Question

javascript/ jquery validation for time log(5h 3m)

I have an input with the type of text. How to validate so that the user can enter only such values (5h 30m), it is for logging time(how much time was spent on a task). Should I use any regexp ?

Answer

I am not sure how to handle all cases at once but you can always test against several rexexp and see if you get a match.

  • Hours and minutes : /^\d{1,2}h\d{1,2}m$/i

  • Hours only : /^\d{1,2}h$/i

  • Minutes only : /^\d{1,2}m$/i

  • Minutes and hours : /^\d{1,2}m\d{1,2}h$/i

var pattern1 = /^\d{1,2}h\d{1,2}m$/i;
var pattern2 = /^\d{1,2}h$/i;
var pattern3 = /^\d{1,2}m$/i;
var pattern4 = /^\d{1,2}m\d{1,2}h$/i;

var reg1 = RegExp(pattern1);
var reg2 = RegExp(pattern2);
var reg3 = RegExp(pattern3);
var reg4 = RegExp(pattern4);

var test = function() {

  var toTest = document.getElementById('i').value;

  if (
    !reg1.test(toTest) &&
    !reg2.test(toTest) &&
    !reg3.test(toTest) &&
    !reg4.test(toTest)
  ) alert('Not OK');
  else alert('OK');
}
<input id="i" type="text" value="" />
<input type="button" value="Test" onclick="test();" />