adsense

Tuesday, September 25, 2018

regex to validate HH:MM AM/PM

Following regex can be used to validate HH:MM AM/PM  time format.

^([0-1]?[0-9]|2[0-3]):[0-5][0-9] [APap][mM]$

e.g
Assuming the timper control has provided class "tod"  following code will validate time when user enters a value and tabbed out/focus out from the control.

Javascript
<script  type="text/javascript">

funciton pageLoad(){
  $(".tod").focusout(function (e) {
            if (e.target.value.trim() !== "") {
                var result = checkTime(e.target.value.trim());
                if (!result) {
                   //invalid time
                }
                else {
                   //clear validation
                }
            }
            else {
                 //clear validation
            }
        });
}

function checkTime(value) {
        var pattern = new RegExp("(^([0-1]?[0-9]|2[0-3]):[0-5][0-9] [APap][mM]$)");
        var result = pattern.test(value);
        return result;
    }

</script>



cheers,
Samitha

No comments:

Post a Comment