Mishra Shreyanshu
Mishra Shreyanshu

Reputation: 644

jQuery validation, Date Format mm/yyyy validates on keyup

I need to validate my input fields before processing it to payment using Stripe.

For card number I created an input box:

<input type="text" class="credit-card" id="cardnumber" name="cardnumber" size="30" value="" placeholder="XXXX-XXXX-XXXX-XXXX">

I validate it in a manner that after every 4 digits it put - automatically:

String.prototype.toCardFormat = function () {
     return this.replace(/[^0-9]/g, "").substr(0, 16).split("").reduce(cardFormat, "");
function cardFormat(str, l, i) {
    return str + ((!i || (i % 4)) ? "" : "-") + l;
   }
};
$(".credit-card").keyup(function () {
      $(this).val($(this).val().toCardFormat());
});

Now I need to validate the date as the user start entering mm, it automatically adds / and make it in format mm/yyyy . So that this should be valid date:

05/2016

but not these:

13/2018
05/2006
5/19
05/19
06-2019
05 2019

Also I used replace method to restrict user to enter ant text and symbols.

Upvotes: 0

Views: 1706

Answers (3)

FelipeFelix
FelipeFelix

Reputation: 11

onkeyup i called the function called mdate>>

function mdata(v){
    v=v.replace(/\D/g,""); //Remove what is not a digit
    v=v.replace(/(\d{2})(\d)/,"$1/$2");       
    v=v.replace(/(\d{2})(\d)/,"$1/$2");       

    v=v.replace(/(\d{2})(\d{2})$/,"$1$2");
    return v;
}

it will display 29/04/2000 and will auto put the "/".

i put this inside the html and it worked for me.

Upvotes: 1

Youssef
Youssef

Reputation: 54

Use a plugin Jquery validate that the best one for validation fields. Check this link below : http://jqueryvalidation.org/creditcard-method/

Upvotes: 1

ABrowBoyGenius
ABrowBoyGenius

Reputation: 73

You can use this API to validate credit card inputs. http://jquerycreditcardvalidator.com/ or check out this blog on validation for Stripe API. https://stripe.com/blog/jquery-payment

Upvotes: 1

Related Questions