DDDD
DDDD

Reputation: 3940

Javascript validation accepting when it shouldn't

I have a script that is checking my email and date fields. They will still accept a bad date. What am I doing wrong? I am new to regex.

<script type="text/javascript">
$('#btn-submit').click(function() {
    $('.error').hide();

    var hasError = false;
    var payError = false;
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    var ccdate = /^((0[1-9])|(1[0-2]))\/((2013)|(20[1-4][0-9]))$/;

//validate email

var emailaddressVal = $("#mail").val();
if(emailaddressVal == '') {
  $("#errors").after('<span class="error">Please enter your email address.</span>');
  hasError = true;
}
else if(!emailReg.test(emailaddressVal)) {
  $("#errors").after('<span class="error">Enter a valid email address.</span>');
  hasError = true;
}

// This checks if the drop down option is selected to show billing fields.

if ( ($("#selection").val() == '') ) {
    $("#errors").after('<span class="error">Please select an option.</span>');
    hasError = true;
 }

if ( ($("#selection").val() == 'charge') ) {
    //validate cctype
    if ( ($("#cctype").val() == '') ) {
      $("#errors").after('<span class="error">Please select a credit card type.</span>');
      payError = true;
    }       

//validate ccdate

    var ccdate = $("#ccdate").val();
    if ( ccdate == '') {
      $("#errors").after('<span class="error">Please enter a date</span>');
      payError = true;
    }
    else if(!date.test(ccdate)) {
        $("#errors").after('<span class="error">Enter a valid date.</span>');
        payError = true;
      }

    if(payError == true) { return false; }
}

if(hasError == true) { return false; }

});

My form has several input fields. I have a drop down that will show the billing table with all the billing fields. I am trying to get it to only accept MM/YYYY as a valid credit card date. This seems to accept any string.

Thank you

Upvotes: 0

Views: 76

Answers (1)

Ry-
Ry-

Reputation: 224952

var ccdate = $("#ccdate").val();

Here, you’re overwriting the regular expression from here:

var ccdate = /^((0[1-9])|(1[0-2]))\/((2013)|(20[1-4][0-9]))$/;

Change the name of the regular expression to date. Also, 2013 and 20[1-4][0-9] don’t need to be in groups.

Upvotes: 4

Related Questions