Javascript Credit Card No and Exp Date Validation - javascript

The thing is, I already figured it out(just copy/paste some codes from stackoverflow). But the thing that only matters for me is; Whenever I enter cc number and hits "Tab", it automatically validates the expiration. I used onchange attribute for the 2 boxes. Please help me adjust my codes.
What i would like for the outcome is..
-When i enter cc number, and hit "Tab" the onchange attribute for cc textbox[validates it] and not yet validating the Expiration textbox[not yet validate].
I have tried everything but it only makes it not work..hehe.. Im sorry guys, im not really good at constructing javascripts. Thank you.
Javascript
<!-- START: VALIDATION IN CREDIT CARDS -->
<script type="text/javascript">
//START: FOR CREDIT CARD NUMBER
function validateCard(card_no){
var Check_MasterCard = /^([51|52|53|54|55]{2})([0-9]{14})$/;
var Check_Visa = /^([4]{1})([0-9]{12,15})$/;
if(Check_Visa.test(card_no)){
document.getElementById('cardSuccess').style.display = "block";
document.getElementById('cardSuccess_1').style.display = "none";
document.getElementById('cardError').style.display = "none";
return true;
}else if(Check_MasterCard.test(card_no)){
document.getElementById('cardSuccess_1').style.display = "block";
document.getElementById('cardSuccess').style.display = "none";
document.getElementById('cardError').style.display = "none";
return true;
}else{
document.getElementById('cardError').style.display = "block";
document.getElementById('cardSuccess_1').style.display = "none";
document.getElementById('cardSuccess').style.display = "none";
return false;
}
}
//END: FOR CREDIT CARD NUMBER
function validateForm(){
// Set error catcher
var error = 0;
// Validate Credit Card
if(!validateCard(document.getElementById('card_no').value)){
error++;
}
if(error > 0){
return false;
}
//FOR EXPIRY VALIDATION
var datereg = /^(0[1-9]|1[012])[- /.](19|20)\d\d+$/;
if (!datereg.test(document.getElementById('credit_card_exp').value)) {
document.getElementById("expiry_error1").style.display="block";
document.getElementById("expiry_error").style.display="none";
return false;
}
var currentDate = new Date(); //this returns the current datetime
//Clear all the other date parts.
currentDate.setDate(0);
currentDate.setHours(0);
currentDate.setMinutes(0);
currentDate.setSeconds(0);
currentDate.setMilliseconds(0);
var year = parseInt(payment_form.credit_card_exp.value.split('/')[1]);
var month = parseInt(payment_form.credit_card_exp.value.split('/')[0]);
var dateToCheck = new Date(year,month,0,0,0,0,0);
if (dateToCheck.getTime() < currentDate.getTime()){
//invalid date
document.getElementById("expiry_error").style.display="block";
document.getElementById("expiry_error1").style.display="none";
return false;
}
document.getElementById("expiry_error").style.display="none";
document.getElementById("expiry_error1").style.display="none";
return true;
//END FOR EXPIRY VALIDATION
}
</script>
<!-- END: VALIDATION IN CREDIT CARDS -->
HTML:
<form id='payment_form' name="payment_form" method="post" action="exec_order_process.php" onsubmit="return validateForm();">
Card Number*
<input class="form-control" onchange="return validateForm();" name="card_no" id="card_no" type="text" maxlength="16" required="required" placeholder="Enter Card number" >
<span class="alert alert-danger changeFont" id="cardError" style="display: none;">You must enter a valid Credit Card for VISA and MasterCard Only<span class="glyphicon glyphicon-remove"></span></span>
<span class="alert alert-success changeFont" id="cardSuccess" style="display: none;">This is a VISA card <span class="glyphicon glyphicon-ok"></span></span>
<span class="alert alert-success changeFont" id="cardSuccess_1" style="display: none;">This is a MasterCard <span class="glyphicon glyphicon-ok"></span></span>
Expiration*
<input onchange="return validateForm();" class="form-control" name="credit_card_exp" id="credit_card_exp" type="text" maxlength="7" onchange="validCCForm(this);" required placeholder="MM / YYYY ">
<label class="error" id="expiry_error" style="display: none;">Credit Card Expired</label>
<label class="error" id="expiry_error1" style="display: none;">Enter valid Date Format</label>
<input type="submit" value="Submit">
</form>

You will have to create 2 Javascript functions:
validateCreditCard and validateExpiration
Then you can use the validateCreditCard function on you credit card input (on change) and validateExpiration on the expiration input.
You can still keep a function validateForm, but this function will simply call the other 2 functions so that all inputs are validated (you can use it for example before submit).

The reason why the expiration date is being validated when the card number input element loses focus is that the onchange attribute of that element calls ValidateForm() which is where you are validating the expiration date.
Refactor the expiration date validation code to a unique function (Single Responsibility Principal).
Remove the duplicate onchange attribute from the credit_card_exp html input element
Refactor the onchange attributes of your input elements as follows:
<label>Card Number*</label>
<input onchange="validateCardNumber(this.value)" class="form-control" name="card_no" id="card_no" type="text" maxlength="16" required="required" placeholder="Enter Card number" />
<label>Expiration*</label>
<input onchange="validateExpirationDate(this.value)" class="form-control" name="credit_card_exp" id="credit_card_exp" type="text" maxlength="7" required placeholder="MM / YYYY " />​
You may like to review the HTML onchange Attribute and JavaScript/HTML Event pages on w3Schools.com website for clarification.

Related

Form Validation Not Resetting After Failing Validation

I'm using a small script to validate a postcode, which works and stops the user entering an invalid password, but when an invalid post code is entered you then can't submit a correct entry. For example, if I enter 'ST' I get the message telling me the postcode is invalid, so without refreshing the page manually I enter 'ST6 1SA' (which is a valid Stoke postcode) and I can't submit the form, I just keep getting the invalid tool tip advising me the post code is not in the correct format.
JS:
<script>
// Validate the postcode before it's sent
(function () {
var postcode = document.getElementById('postcode-entry');
var wrapper = document.getElementById('validation');
var notify = document.createElement('div');
var mnisLookup = document.getElementById('mnis-results');
var matchingClients = document.getElementById('matching-clients');
var postcodeWrapper = document.getElementById('postcode-wrapper');
notify.id = 'notify';
notify.style.display = 'none';
wrapper.appendChild(notify);
postcode.addEventListener('invalid', function (event) {
if (!event.target.validity.valid) {
notify.textContent = 'Please enter a valid postcode e.g. ST1, ST1 4BJ';
notify.className = 'error';
notify.style.display = 'block';
postcode.className = 'form-control invalid';
}
});
})();
</script>
HTML:
<form id="postcode-wrapper" class="form-horizontal">
<div id="postcode-lookup" class="form-group">
<label for="postcode-entry" class="col-sm-1">Postcode:</label>
<div id="postcode-entry-wrapper" class="col-sm-3">
<input type="text" pattern="^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y])))( {0,}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2})?))$" oninvalid="setCustomValidity('Invalid Post Code Format ')" class="form-control" id="postcode-entry" placeholder="Enter your postcode" name="Postcode" />
</div>
<div class="col-sm-1">
<input id="search" type="submit" value="Search" class="btn btn-default" />
</div>
<div id="validation" class="col-sm-7"></div>
</div>
</form>
Just a quick note that may affect how the page is refreshing, this is inside an MVC Razor page and wrapped with Html.BeginForm - not sure if that makes a difference?
While debugging your code, i found that the event.target.validity.valid was returning false even if the input was valid e.g. 'ST6 1SA'. This was occuring because it does not update the custom validation for the new input and the previous state persists even after entering the valid input.
So to update and reset the previous validation, you have to reset setCustomValidity('') on input change, i.e. oninput="setCustomValidity('')"
Please replace this code:
<input type="text" pattern="^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y])))( {0,}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2})?))$" oninvalid="setCustomValidity('Invalid Post Code Format ')" class="form-control" id="postcode-entry" placeholder="Enter your postcode" name="Postcode" oninput="setCustomValidity('')"/>

How to implement form validations for Dynamically generated Form fields

I have a page in my Angular application where all form fields are created dynamically based on data coming from backend.
<div class="col-md-12">
<form class="form-inline" name="reportsForm">
<div class="form-group form-group-grid" ng-repeat="fields in selectedTabData.requiredField" ng-switch="fields.paramType">
<label>{{fields.paramName}}<span class="asterisk" ng-if="fields.mandatory==true">*</span></label>
<input type="number" class="form-control" ng-switch-when="Number" ng-model="fields.fieldValue" ng-required="fields.mandatory">
<input type="date" data-date-format="mm/DD/YYYY" class="form-control" ng-switch-when="DatePicker" ng-model="fields.fieldValue" ng-required="fields.mandatory">
<input type="text" class="form-control" ng-switch-when="Text" ng-model="fields.fieldValue" ng-required="fields.mandatory">
<select type="date" class="form-control" ng-switch-when="DropDown" ng-options="field.paramKey as field.paramValue for field in fields.paramData" ng-model="fields.fieldValue" ng-required="fields.mandatory">
</select>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary form-inline-grid-button" ng-click="getReport()">Run Report</button>
</div>
</form>
<span style="color:red">Please enter all the required fields marked with (*)</span>
</div>
I need the validation error message to be shown if anyone of the required field in the form is left empty.
The form fields data coming from backend is assigned in $scope.selectedTabData.requiredField
$scope.selectedTabData.requiredField.forEach(function(item)
{
if(item.paramType == "DatePicker")
{
var date = new Date(item.fieldValue);
var formattedDate = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
paramValue.push(formattedDate);
paramName.push(item.paramName);
}
else
{
if(item.mandatory == true && item.fieldValue == undefined){
//need to set validation as failed
}else{
//need to set validation as passed
}
paramValue.push(item.fieldValue);
paramName.push(item.paramName);
}
})
This is the condition I need to check to validate the form :
if(item.mandatory == true && item.fieldValue == undefined){
//need to set validation as failed
}else{
//need to set validation as passed
}
This is the first time I am working with dynamic fields, can anyone help me with implementation of validation in this case?
Thanks.
So to fix this, I had to deal with this the basic way.
I created a scope variable and set it as a flag.
in HTML :
<div>
<span ng-if="formInvalid" style="color:red">Please fill in all the required fields(*)</span>
</div>
In Controller :
$scope.formInvalid = false;
if(item.mandatory == true && item.fieldValue==null)
{
$scope.formInvalid = true;
}
This worked out for me. Please add more answers if you have an alternate solution to handle validations in dynamic elements.

HTML5 custom validation for passwords

I'm looking to create an HTML5 custom validation message when I enter 2 passwords which don't match.
Here's my HTML and JQuery
HTML:
<form class="form-group main-settings-form" id="main-settings-form-password">
<input class="form-control main-settings-form-input password-main" type="password" placeholder="Enter new password" id="new-password" pattern='(?=.*\d)(.{6,})' required>
<input class="form-control main-settings-form-input" type="password" placeholder="Retype new password" id="confirm-password" pattern='(?=.*\d)(.{6,})' required>
<div class="main-settings-form-buttons">
<button type="button" class="btn btn-danger settings-edit-cancel">Cancel</button>
<button class="btn btn-success" type="submit">Save</button>
<br>
<br>
Forgot password?
</div>
</form>
JS:
$(document).ready(function () { //This confirms if the 2 passwords match
$('#confirm-password').on('keyup', function (e) {
var pwd1 = $("#new-password").get(0);
var pwd2 = $("#confirm-password").get(0);
pwd2.setCustomValidity("");
if (pwd1 != pwd2) {
document.getElementById("confirm-password").setCustomValidity("The passwords don't match"); //The document.getElementById("cnfrm-pw") selects the id, not the value
}
else {
document.getElementById("confirm-password").setCustomValidity("");
//empty string means no validation error
}
e.preventDefault(); //would still work if this wasn't present
});
});
The problem is, the message is always triggered even if the passwords do match. Please help me trigger the message only when the passwords dont match, and be allowed to safely submit when they do.
JS fiddle: https://jsfiddle.net/kesh92/a8y9nkqa/
password requirements in the fiddle: 6 characters with atleast one number
jQuery get() returns the dom elements of each...they can never be equal
You want to compare values.
Try changing
if (pwd1 != pwd2) { //compare 2 dom nodes
To
if ( pwd1.value != pwd2.value) { //compare 2 dom node values
Note however that you also need to now consider empty values since you are over riding validty

Using HTML form field validation

I am using jQuery Mobile and am attempting to use HTML5 form field validation to perform inline form field validation. I am doing this because I really like the way that the browser reports issues in the bubble and I don't think it is very user friendly to wait until someone has completed filling out a form and then tell them what is wrong. Here is my HTML:
<form id="frmMain" action="#">
<input type="checkbox" data-enhance="false" value="1" id="cbxFB" />
<label for="cbxFB">
<span class="formsubtext">Check this box to use Facebook information to help fill out this registration. Once registered you will be able to use the Facebook login button.</span>
</label>
<label for="tbEmail">*Email</label><input type="email" id="tbEmail" required autofocus placeholder="example#address.com" />
<label for="tbPassword">*Password</label><input type="password" id="tbPassword" required />
<div class="formsubtext" style="margin-top:1px; padding-top:0px; margin-bottom:10px">Minimum of 6 characters, one capital character, and one lower case character.</div>
<label for="tbPasswordConfirm">*Password Confirm</label><input type="password" id="tbPasswordConfirm" required />
<label for="tbPin">*Account Pin</label><input type="password" pattern="[0-9]{4}" id="tbPin" required placeholder="####" />
<div class="formsubtext" style="margin-top:1px; padding-top:0px; margin-bottom:10px">A four digit number that you will remember. This value will be needed to perform sensitive tasks within the application.</div>
<label for="tbFName">*First Name</label><input type="text" id="tbFName" required />
<label for="tbLName">*Last Name</label><input type="text" id="tbLName" required />
<label for="tbPhone">Phone Number</label><input type="tel" id="tbPhone" pattern="\d{3}[\-]\d{3}[\-]\d{4}" placeholder="###-###-####" style="margin-bottom:1px; padding-bottom:0px;" />
<div class="formsubtext" style="margin-top:1px; padding-top:0px; margin-bottom:20px;">Used at your option when you schedule an appointment with a service provider</div>
<div style="display:none;"><label for="tbfbID">Facebook ID</label><input type="text" id="tbfbID" /></div>
<input type="submit" id="btnMainNext" data-icon="arrow-r" data-iconpos="right" value="Next" data-theme="c" class="ui-btn-c ui-btn ui-corner-all" />
</form>
For the confirm password form field I have the following event defined:
$("#tbPasswordConfirm").on("change", function (event) {
var password = $("#tbPassword").val();
var passwordconfirm = $("#tbPasswordConfirm").val();
if (password != passwordconfirm) {
$("#tbPasswordConfirm")[0].setCustomValidity("The value entered does not match the previous password entered.");
$("#btnMainNext").click();
}
else {
$("#tbPasswordConfirm")[0].setCustomValidity("");
}
$(this).focus().select();
})
My problem is that when the user enters something into the field and moves to the next field the HTML form validation shows the error message for the next field (which is required). I want it to show the message for the field they just left. How do I stop the focus from moving to the next field so that the bubble message that shows up is from the field they just entered the data into? As you can see I have tried setting the focus but that does not work. Any help would be greatly appreciated.
You can stop focus from moving to the next field but you can't trigger native validation UI or error message unless you click submit button.
To stop focus from moving next field, after you set the custom validity on the field, you can use:
$('#tbPasswordConfirm').blur(function(event) {
event.target.checkValidity();
}).bind('invalid', function(event) {
setTimeout(function() { $(event.target).focus();}, 50);
});
The blur() function will check the validity on blur and if it would be invalid, the corresponding function in bind() would set the focus back to that element.
Solved it
Fiddle
$(function() {
$("#tbPasswordConfirm").on("input", function(event) {
var thisField = $("#tbPasswordConfirm")[0],
theForm = $("#frmMain")[0],
password = $("#tbPassword").val(),
passwordconfirm = $(this).val(),
custom = password === passwordconfirm ? "" : "The value entered does not match the previous password entered.";
thisField.setCustomValidity(custom);
if (!theForm.checkValidity()) theForm.reportValidity();
});
});
You can use html tabindex attr to manipulate which element will get the focus when you click tab character. See docs to how to use it.
For example, if you make your password confirm input as tabindex="5", you can add tabindex="6" to the <label for="tbPin"> element to prevent next input from focusing right after.

How to validate radio and array before submitting form?

I need to validate two things on this form:
1. There are two radio buttons:
• OPTION 1 - On click function hides mm/dd/yyyy fields for OPTION 2
• OPTION 2 - On click function shows mm/dd/yyyy fields which aren't required.
2. Zip code field - Need to validate an array of acceptable zip codes.
I've got this form MOSTLY working aside from a few issues:
1. If you click submit without checking or filling out anything it replaces some of the text on the page with the word "Invalid" and vice versa when valid info has been filled in.
2. It does not go to the next page if valid info has been submitted.
3. It only validates the zipcode field and does not require the radio buttons.
Any help would be greatly appreciated! Thanks!
Test page here: http://circleatseven.com/testing/jquery/zipcodevalidation/
If i have you understand you search for this:
I dont have write a Message with "invalid", i give an alert.
In your HTML add "onsubmit" to your form-Tag:
<form method="post" action="success.php" id="step1" onsubmit="checkdata();">
and add a submit-Button to your form or trigger on your pseudo-submit-button .submit() with jQuery.
In your Javascript you add following function:
function checkdata() {
if ($(":radio:checked").length < 1) {
alert('Please choose an Option!');
return false;
}
zipCodeOk = false;
zipCodes = new Array(75001, 75002, 75006); //Your Zip-Codes
for (var i = 0; i <= zipCodes.length; i++) {
if ($('#enterZip').val() == zipCodes[i]) {
zipCodeOk = true;
break;
}
}
if (!zipCodeOk) {alert('Please enter a valid Zip-Code!');return false;}
}
A friend helped me out.. We ended up using the Jquery validate plugin - here's what we came up with:
<script type="text/javascript">
$(document).ready(function(){
jQuery.validator.addMethod("validZip", function(value) {
var zips=['12345', '23456', '34567', '45678', '56789', '67890', '78901', '89012', '90123', '01234'];
if ($.inArray(value,zips) > -1) {
return true;
} else {
return false;
}
}, "invalid zip");
$("#step1").validate({
rules: {
currentServiceStatus: "required",
enterZip: { validZip : true }
}
});
$('.moveInDates').hide();
$(":radio:eq(0)").click(function(){
$('.moveInDates').hide();
});
$(":radio:eq(1)").click(function(){
$('.moveInDates').show();
});
});
</script>
And here's the html:
<form method="post" action="success.php" id="step1">
<h1>CHOOSE *</h1>
<input name="currentServiceStatus" type="radio" value="Switch Me" /> OPTION 1
<br/>
<input name="currentServiceStatus" type="radio" value="Move-In" /> OPTION 2 (reveals more fields on click)
<div id="dateInputs" class="moveInDates">
<h2>Move-In Date (not required)</h2>
<p><span class="mmddyyyy"><input name="moveInDateMonth" type="text" class="text" id="moveInDateMonth" /> / <input name="moveInDateDay" type="text" class="text" id="moveInDateDay" /> / <input name="moveInDateYear" type="text" class="text" id="moveInDateYear" /></span>
</div>
<hr/>
<h1>ZIP CODE *</h1>
<p>Enter one of the following acceptable Zip Codes:</p>
<p>12345, 23456, 34567, 45678, 56789, 67890, 78901, 89012, 90123, 01234</p>
<input name="enterZip" type="text" class="text" id="enterZip" />
<hr/>
<input type="image" id="submitButton" src="http://circleatseven.com/testing/jquery/zipcodevalidation/library/images/btn_submit.jpg" />
<p><em>* Required</em></p>
</ul>

Categories