Skip to content

Commit

Permalink
Add checkout validation
Browse files Browse the repository at this point in the history
  • Loading branch information
imranhsayed committed May 8, 2021
1 parent 44eed42 commit 1d99a43
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 6 deletions.
9 changes: 6 additions & 3 deletions src/components/checkout/CheckoutForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,10 +115,13 @@ const CheckoutForm = ({countriesData}) => {
/**
* Validate Billing and Shipping Details
*
* Note: If billing is different than shipping address, only then validate billing.
* Note:
* 1. If billing is different than shipping address, only then validate billing.
* 2. We are passing theBillingStates?.length and theShippingStates?.length, so that
* the respective states should only be mandatory, if a country has states.
*/
const billingValidationResult = input?.billingDifferentThanShipping ? validateAndSanitizeCheckoutForm(input?.billing) : {errors: null, isValid: true};
const shippingValidationResult = validateAndSanitizeCheckoutForm(input?.shipping);
const billingValidationResult = input?.billingDifferentThanShipping ? validateAndSanitizeCheckoutForm(input?.billing, theBillingStates?.length) : {errors: null, isValid: true};
const shippingValidationResult = validateAndSanitizeCheckoutForm(input?.shipping, theShippingStates?.length);

if (!shippingValidationResult.isValid || !billingValidationResult.isValid) {
setInput({
Expand Down
5 changes: 2 additions & 3 deletions src/validator/checkout.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import validator from 'validator';
import isEmpty from './isEmpty';


const validateAndSanitizeCheckoutForm = ( data ) => {
const validateAndSanitizeCheckoutForm = ( data, hasStates = true ) => {

let errors = {};
let sanitizedData = {};
Expand Down Expand Up @@ -62,7 +62,6 @@ const validateAndSanitizeCheckoutForm = ( data ) => {
errors[ fieldName ] = `${errorContent} is required`;
}


// If no errors
if ( ! errors[ fieldName ] ) {
sanitizedData[ fieldName ] = validator.trim( data[ fieldName ] );
Expand All @@ -79,7 +78,7 @@ const validateAndSanitizeCheckoutForm = ( data ) => {
addErrorAndSanitizedData( 'address1', 'Street address line 1', 12, 100,'string',true );
addErrorAndSanitizedData( 'address2', '', 0, 254, 'string', false );
addErrorAndSanitizedData( 'city', 'City field', 3, 25, 'string', true );
addErrorAndSanitizedData( 'state', 'State/County', 0, 254, 'string', true );
addErrorAndSanitizedData( 'state', 'State/County', 0, 254, 'string', hasStates );
addErrorAndSanitizedData( 'postcode', 'Post code', 2, 10, 'postcode', true );
addErrorAndSanitizedData( 'phone', 'Phone number', 10, 15, 'phone', true );
addErrorAndSanitizedData( 'email', 'Email', 11, 254, 'email', true );
Expand Down

0 comments on commit 1d99a43

Please sign in to comment.