Payments Scheme

Schema Validation

Detailed guide on validation mechanics and code libraries in front-end and back-end servers.

Once you have gathered user input, you should validate the assembled data object dynamically against the schema provided by the Payment Rules services. Validating this data guarantees that you're sending the data to the API as expected and reduces API errors.

Front-end Validation with AJV

AJV is the fastest JSON Schema validator for Node.js and the browser, supporting draft-2020-12 schemas out of the box. Usually, in a front-end application, you maintain a form state (using libraries like React Hook Form, Formik, or plain React state) that gathers user input as a structured object. This object is then validated against the Payment Rules Schema before submission.

Setup and Example

First, install the package:

npm install ajv ajv-formats

Then configure AJV to validate your form states (e.g., your formData object):

Example using AJV
import Ajv from "ajv/dist/2020";
import addFormats from "ajv-formats";
import schema from "./swift-payment-rule-schema.json";

// 1. Initialize AJV specifically for draft-2020-12
const ajv = new Ajv({ allErrors: true });
addFormats(ajv);

// 2. Compile your fetched schema
const validate = ajv.compile(schema);

// 3. Process your form data
const formData = {
  creditor_name: "John Doe",
  creditor_postal_address: {
    address_line: ["123 Fake Street", "Apt 2B"],
    town_name: "New York",
    country: "US"
  },
  creditor_account_and_agent: {
    other_identification: "123456789",
    clearing_member_identification: "987654321" // ABA
  }
};

const valid = validate(formData);

if (!valid) {
  console.log("Validation Errors: ", validate.errors);
  // Match validate.errors to the x-UIErrorMessage object in the schema mappings!
} else {
  console.log("Form data is completely valid and ready for submission!");
}

Back-end Validation

Because the web is open by design, it introduces certain security risks. You should always double-validate the incoming payload on your back-end server by comparing requests to the same underlying Schema documents.

Node.js

Since you have access to AJV in any JavaScript context, Node.js validation is identical to the front-end (AJV) strategy seen above. This simplifies full-stack development.

Java (networknt/json-schema-validator)

For Spring Boot or other Java applications, the recommended approach is using networknt which properly supports Schema Draft 2020-12.

import com.networknt.schema.JsonSchema;
import com.networknt.schema.JsonSchemaFactory;
import com.networknt.schema.SpecVersion;
import com.networknt.schema.ValidationMessage;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Set;

public class SchemaValidator {
    public static void validateRequest(String jsonPayload, String schemaString) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode nodeToValidate = mapper.readTree(jsonPayload);
        JsonNode schemaNode = mapper.readTree(schemaString);

        JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V202012);
        JsonSchema schema = factory.getSchema(schemaNode);

        Set<ValidationMessage> errors = schema.validate(nodeToValidate);

        if (!errors.isEmpty()) {
            throw new RuntimeException("Validation failed: " + errors.toString());
        }
    }
}

Python (jsonschema)

To validate in Python, you simply need the ubiquitous jsonschema pip package.

import jsonschema
from jsonschema import validate
import json

schema = {
     "$schema": "https://json-schema.org/draft/2020-12/schema",
     # ... SWIFT payment schema
}

payload = {
    "creditor_name": "Test Organization",
    # ... Other payload fields
}

try:
    validate(instance=payload, schema=schema)
    print("Valid!")
except jsonschema.exceptions.ValidationError as err:
    print(f"Validation Error: {err.message}")

Golang (santhosh-tekuri/jsonschema)

For Go applications, santhosh-tekuri/jsonschema is a highly performant and compliant validator supporting Draft 2020-12.

package main

import (
    "encoding/json"
    "fmt"
    "log"

    "github.com/santhosh-tekuri/jsonschema/v5"
)

func main() {
    // Initialize compiler and enable draft 2020-12
    compiler := jsonschema.NewCompiler()
    compiler.Draft = jsonschema.Draft2020

    // Load your schema
    schema, err := compiler.Compile("schema.json")
    if err != nil {
        log.Fatalf("Failed to compile schema: %v", err)
    }

    // Parse your payload
    jsonPayload := []byte(`{"creditor_name": "Test Organization"}`)
    var payload interface{}
    if err := json.Unmarshal(jsonPayload, &payload); err != nil {
        log.Fatalf("Failed to parse payload: %v", err)
    }

    // Validate
    if err := schema.Validate(payload); err != nil {
        fmt.Printf("Validation failed: %#v\n", err)
    } else {
        fmt.Println("Payload is completely valid!")
    }
}

.NET / C# (JsonSchema.Net)

For .NET developers building back-end APIs, the JsonSchema.Net library supports Draft 2020-12.

using System;
using System.Text.Json;
using Json.Schema;

class Program
{
    static void Main()
    {
        // Load the Swift Payment Rules schema
        var schemaMap = JsonSchema.FromFile("schema.json");

        // The data payload evaluating
        string jsonPayload = @"{ ""creditor_name"": ""Test Organization"" }";
        using var document = JsonDocument.Parse(jsonPayload);

        // Evaluate using hierarchical output format for detailed errors
        var options = new EvaluationOptions
        {
            OutputFormat = OutputFormat.Hierarchical
        };

        var results = schemaMap.Evaluate(document.RootElement, options);

        if (results.IsValid)
        {
            Console.WriteLine("Payload is completely valid!");
        }
        else
        {
            Console.WriteLine("Validation failed!");
            // Iterate and handle the validation errors
        }
    }
}

On this page