Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a zero before a single digit date in javascript [closed]

I am validating date field using javascript and there i need to validate the DD/MM/YY

if the user enter the date as 10/06/2012 it will be valid

if the user enter the date as 3/06/2012 means we need to add a zero before the date as 03/06/2012.

my javascript code is

$('#date').blur(function () {
            var collector = $('#date').val();
            collector = collector.split("/");
            if (collector[0].length != 2) {
                if (collector[0].length == 1) {
                    //here code for make it as two digit
                }
            }
            else
            {
             alert('Date is not entered properly');
            }
});

my html

Date: <input type="text" id="date" name="date" />

How to do it with javascript

like image 548
Krish Avatar asked Aug 01 '26 02:08

Krish


1 Answers

Try this :

collector[0] = "0" + collector[0];

with your code :

$('#date').blur(function() {
    var collector = $('#date').val();
    collector = collector.split("/");
    if (collector[0].length != 2) {
        if (collector[0].length == 1) {
            collector[0] = "0" + collector[0];
        }
    }
    else {
        alert('Date is not entered properly');
    }
    // set the val again
    $('#date').val(collector.join('/'));
});​

Working example here

like image 145
Manse Avatar answered Aug 02 '26 14:08

Manse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!