validate()

Initiates validation on all hosted fields configured for selected paymentType. Validation results are collected into a single object and provided in the callback. This validation method performs only basic validation in the browser, additional validation is later performed on the gateway when you call the updateSessionFromForm() method. Therefore you must also handle all errors returned from the formSessionUpdate callback triggered by the updateSessionFromForm() method.

This function supports the Multiple Hosted Session functionality.

Usage

PaymentSession.validate(paymentType, callback, [scope])

Example

PaymentSession.validate('card', function (result) {
    // HANDLE VALIDATION RESULTS
    if (result.card) {

        //check if all hosted fields are valid
        if (result.card.isValid) {
            console.log('All hosted fields of "card" paymentType are valid');
        } else {
            //CHECK WHICH FIELDS ARE INVALID

            //check card number results
            if (result.card.number) {
                var cardNumber = result.card.number;

                //check if card number is valid
                if (cardNumber.isValid) {
                    console.log('Card number is valid.');
                } else {
                    if (cardNumber.isIncomplete) {
                        console.log('Card number is incomplete, please enter full card number.');
                    }
                    if (cardNumber.hasError) {
                        console.log('Error has been detected on Card number field.');
                    }
                    if (cardNumber.errorReason) {
                        switch (cardNumber.errorReason) {
                            case 'EMPTY':
                                console.log('Card number is mandatory field, please enter card number.');
                                break;
                            case 'INVALID_CHARACTERS':
                                console.log('There is invalid character in card number.');
                                break;
                            case 'NOT_SUPPORTED':
                                console.log('The card number you entered is not supported.');
                                break;
                            case 'INVALID_VALUE':
                                console.log('The card number you entered is incorrect, please check the number and try again.');
                                break;
                            case 'INVALID_LENGTH':
                                console.log('The card number you entered is too long.');
                                break;
                            case 'AWAITING_SERVER_RESPONSE':
                                console.log('Card type is being determined. Please try again.');
                                break;
                            case 'TIMEOUT':
                                console.log('We can not determine the card type. You can proceed updating card number or reload the page.');
                                break;
                            case 'NOT_AUTHORIZED':
                                console.log('Request is not authorized, your session is probably expired. Please reload the page.');
                                break;
                            case 'SYSTEM_ERROR':
                                console.log('System error occurred. Please reload the page.');
                                break;
                            case 'SESSION_AUTHENTICATION_LIMIT_EXCEEDED':
                                console.log('You have exceeded session authentication limit. Please reload the page in order to generate new sessionId.');
                                break;
                            default:
                                break;
                        }
                    }
                    //get selector of the invalid field
                    console.log(cardNumber.selector);
                }

                //check Expiry month results
                if (result.card.expiryMonth) {
                    var expiryMonth = result.card.expiryMonth;

                    //check if Expiry month is valid
                    if (expiryMonth.isValid) {
                        console.log('Expiry month is valid.');
                    } else {
                        if (expiryMonth.isIncomplete) {
                            console.log('Card number is incomplete, please enter the value between [1 - 12].');
                        }
                        if (expiryMonth.hasError) {
                            console.log('Error has been detected on Expiry month field.');
                        }
                        if (expiryMonth.errorReason) {
                            switch (expiryMonth.errorReason) {
                                case 'EMPTY':
                                    console.log('Expiry month is mandatory field, please enter Expiry month.');
                                    break;
                                case 'INVALID_CHARACTERS':
                                    console.log('There is invalid character in Expiry month.');
                                    break;
                                case 'INVALID_VALUE':
                                    console.log('The Expiry month you entered is incorrect.');
                                    break;
                                default:
                                    break;
                            }
                        }
                        //get selector of the invalid field
                        console.log(expiryMonth.selector);
                    }
                }

                // check other fields in "result.card" object
            }
        }
    }
});

JSON Example for Validation Result

// errorReason can be one of the following:

/**
 * General <errorReason> values:
 *
 * - EMPTY
 * - INVALID_CHARACTERS
 * - INVALID_VALUE
 * - INVALID_LENGTH
 */

/**
 * Card Number specific <errorReason> values:
 *
 * - AWAITING_SERVER_RESPONSE
 * - NOT_SUPPORTED
 * - TIMEOUT
 * - NOT_AUTHORIZED
 * - SYSTEM_ERROR
 * - SESSION_AUTHENTICATION_LIMIT_EXCEEDED
 */

/**
 * Expiry Year specific <errorReason> values:
 *
 * - EXPIRED
 */

/**
 * Account Number Confirmation specific <errorReason> values:
 *
 * - MISMATCH
 */

// validation result for "card" paymentType
{
    card: {
        isValid: false,
        nameOnCard: {
            "isValid": true,
            "isIncomplete": false,
            "hasError": false,
            "selector": "#card-holder-name"
        },
        number: {
            "isValid": false,
            "isIncomplete": false,
            "hasError": true,
            "errorReason": "INVALID_LENGTH",
            "selector": "#number"
        },
        expiryMonth: {
            "isValid": true,
            "isIncomplete": false,
            "hasError": false,
            "selector": "#expiry-month"
        },
        expiryYear: {
            "isValid": true,
            "isIncomplete": false,
            "hasError": false,
            "selector": "#expiry-year"
        },
        securityCode: {
            "isValid": true,
            "isIncomplete": false,
            "hasError": false,
            "selector": "#security-code"
        }
    }
}

Arguments

paymentType String COMPULSORY

The payment type to update in the session. Valid values are: 'card', 'ach', 'giftCard', 'directDebitCanada'.

<callbackFunction> Function COMPULSORY

The callback function will be invoked with a single argument - validation result object.

  1. result - (Object) Object map containing validation results of all hosted fields for selected payment type.

    <PaymentType> - (Object) Object containing validation results for selected payment type. <PaymentType> object key is equal to one of the following values: ['card', 'ach', 'giftCard', 'directDebitCanada']. Object contains <isValid> property and all <HostedFieldRole> properties for selected payment type. For example, if <PaymentType> is card then it will contain the following properties: ['isValid', 'nameOnCard', 'number', 'expiryMonth', 'expiryYear', 'securityCode'].

    isValid
    (Boolean) Indicates validity status of all hosted fields for selected payment type. Will be equal to <true> only if all hosted fields are valid otherwise <false>.

    <HostedFieldRole> - (Object) Object containing validation result for specific hosted field. <HostedFieldRole> object key is equal to one of the following values: ['nameOnCard', 'number', 'expiryMonth', 'expiryYear', 'securityCode', 'pin', 'bankAccountNumber', 'bankAccountNumberConfirmation', 'bankAccountHolder', 'routingNumber', 'financialInstitutionNumber', 'transitNumber'].

    • isValid
    (Boolean) Indicates validity status of the hosted field.
    • isIncomplete
    (Boolean) Indicates the completeness status of the hosted field. For example, Card Number field containing only 1 digit is incomplete.
    • hasError
    (Boolean) Indicates if hosted field has any validation error. Incomplete value is not considered as an error.
    • errorReason
    (String) The error code which indicates the reason of the validation failure. This property is only supplied when <hasError> property is equal to true.
    • selector
    (String) Identifier of the HTML element that has changed (i.e. "#card-number").

In case of error, validation result object will contain errorReason property. The following errorReason values occur from invalid data entry by the Payer:

errorReason Description Possible error cause Resolution
EMPTY Occurs when a mandatory field is empty. Payer skips a required field such as Card Number. Prompt Payer to provide input for the mandatory field.
EXPIRED Occurs when the card is expired. Triggered only on Expiry Year field. Payer has input an expiry year of 2019, yet the current year is 2020. Prompt Payer to use card that is not expired.
INVALID_CHARACTERS Occurs when invalid characters are present in the hosted field. Payer inputs letters in the year field, such as 'abcd' instead of '2020'. Prompt Payer to verify the value entered.
INVALID_LENGTH Occurs when the value has invalid length. Card brand is determined as Mastercard and the number consists of 13 digits which is invalid length for Mastercard. Prompt Payer to verify the value entered.
INVALID_VALUE Occurs when the value in the hosted field is invalid.
  • • Card Number fails Luhn checksum validation
  • • Expiry Month is not within the range of 1-12
  • • Expiry Year is more than 20 years ahead of the current date
Prompt Payer to verify the value entered.
NOT_SUPPORTED Occurs when the card number is not supported by the merchant. Triggered only on Card Number field. The merchant's gateway configuration or acquirer does not accept that card type. Prompt payer to use another card.
MISMATCH Occurs when Bank Account Number value does not match Bank Account Number Confirmation value. Triggered only on Bank Account Number Confirmation field. Payer entered mismatching confirmation Account Number. Prompt payer to enter the same value in the Bank Account Number and Bank Account Number Confirmation field.

The following errors are applicable only to the Card Number field. The Card Number is validated by the payment gateway and this activity may fail for the reasons below. This is the list of all possible errorReason values the integration must handle:

errorReason Description Possible error cause Resolution
AWAITING_SERVER_RESPONSE Occurs when waiting for gateway validation to complete. Validation of the card number is performed by the payment gateway and depending on the Payer's Internet connection may take several seconds to complete. Wait a few seconds and try the function again. Alternatively use `PaymentSession.onValidityChange(['card.number'], callback)` callback function. This callback function won't be triggered until the payment gateway has responded.
NOT_AUTHORIZED Occurs when user is not authorized to perform a request. Session has expired due to the payer taking too long to make a payment. Create a new session id, and reload the page.
SESSION_AUTHENTICATION_LIMIT_EXCEEDED Each time the first 10 card number digits are changed, the session.js sends an XHR call to the gateway to determine the card brand. By default, the payer can only change first 10 digits only 5 times. Payer has entered too many different cards and exceeded the session limit. Merchants can increase this limit up to 25 times by setting the <session.authenticationLimit> parameter in CREATE_SESSION operation to 25.
SYSTEM_ERROR Occurs when there is a system error on the gateway. An unexpected error on the payment gateway. Prompt Payer to reload the page and try again.
TIMEOUT Occurs when the gateway does not respond after 3 attempts. Each attempt has 10 seconds timeout. An issue with the payer's Internet connection. Prompt Payer to reload the page and try again.

scope String OPTIONAL

The optional named instance of a card payment data set within a session. See Multiple Hosted Sessions for more information.

Return Value

None

Copyright © 2023 MasterCard