Al Augustin
Al Augustin

Reputation: 160

Enter digits into a masked input field in a free form format using jQuery

I would like to build a form input using the mask plug-in that will change the characteristic of the entry for time to permit the user to enter digits in a free form format and the system will convert the entered digits into proper time display using jQuery.

Example: the user to enter “135” and the system to convert this to “01:35”

The code for the mask is:

$("input.time").mask("99:99");

So far I have the code below:

$(document).ready(function() {
$('#awareness-hour').blur(function() {
    if(!$('#awareness-hour').val().match(/([0-1][0-9]|2[0-3]):[0-5][0-9]/)){
        alert('invalid');           
    }else{
        return true;
    };
});
});

Upvotes: 3

Views: 1753

Answers (1)

cbayram
cbayram

Reputation: 2259

This will correct the scenario you mentioned and update the input only if it's a valid time according to your second regular expression. Hopefully, you get the idea and this works:

$("input.time").blur(function() {       
    var userInput = $(this).val().replace(/^([0-9])([0-9]):([0-9])_$/, "0$1:$2$3");     
    if(!userInput.match(/([0-1][0-9]|2[0-3]):[0-5][0-9]/)){
        alert('invalid');           
    }else{
        $(this).val(userInput);
        return true;
    };
}).mask("99:99");

Upvotes: 2

Related Questions