简体   繁体   中英

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

Try:

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

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

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. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM