Klapsius
Klapsius

Reputation: 3359

date format validation with jquery

I am trying to validate the date format (from datepicker) If the date format is right then go to next step if wrong then alert

if ($("#date").val() != (/^\d{2}\/\d{2}\/\d{4}$/)) {
  $("#date").css('background-color', '#FF0000');
}
else {
  alert("good");
}

But this script does not work

Upvotes: 1

Views: 93

Answers (3)

Edward
Edward

Reputation: 1914

Try:

if (!(/^\d{2}\/\d{2}\/\d{4}$/).test($("#date").val())) {
  $("#date").css('background-color', '#FF0000');
}
else {
  alert("good");
}

Upvotes: 2

Nirav Mehta
Nirav Mehta

Reputation: 7063

Look at this code helps:

function call()
{
    if ($("#date").val().search((/^\d{2}\/\d{2}\/\d{4}$/))>-1) {
        $("#date").css('background-color', '#FF0000');
    }
    else {
        alert("good");
    }
}

Hope this helps and answers your question and also for this thread. :)

Upvotes: 0

Camille Hodoul
Camille Hodoul

Reputation: 386

you should try :

if (!/^\d{2}\/\d{2}\/\d{4}$/.test($("#date").val())) {
  $("#date").css('background-color', '#FF0000');
}
else {
  alert("good");
}

You can't compare a string to a RegExp object with == or != operators, you have to use Regexp methods. see mdn

Upvotes: 1

Related Questions