This page explains how to perform Turkish ID number validation in JSON format using Groovy script policy.
This groovy code first checks the character length of the Turkish ID number. If appropriate, it validates the Turkish ID number with a specific algorithm. These validation steps involve certain mathematical calculations of the Turkish ID number. In case of any error, an appropriate error message is assigned to the requestErrorMessageToTargetAPI variable and the request is prevented from going to the backend.
Groovy Script
import groovy.json.JsonSlurper
// Create a parser to process JSON data
def parser = new groovy.json.JsonSlurper()
// Parse incoming JSON data
def jsonResp = parser.parseText(requestBodyTextFromClient)
// Get Turkish ID numbers from JSON
def requestingUserIdentityCardNo = jsonResp.requestingUserIdentityCardNo
def requestedIdentityCardNo = jsonResp.requestedIdentityCardNo
// Method to validate Turkish ID number
def validateTCKN(variableToCheck) {
// Check the length and validity of the Turkish ID number
if (!variableToCheck || variableToCheck.length() != 11) {
requestErrorMessageToTargetAPI = 'Please send a valid parameter: ' + variableToCheck + '.'
} else {
// Validate Turkish ID number mathematically
def tcArr = variableToCheck.substring(0, 11).split('')
def tek = tcArr[0].toInteger() + tcArr[2].toInteger() + tcArr[4].toInteger() + tcArr[6].toInteger() + tcArr[8].toInteger()
def cift = tcArr[1].toInteger() + tcArr[3].toInteger() + tcArr[5].toInteger() + tcArr[7].toInteger()
tek = tek * 7
def sonuc = tek - cift
// Create error message in case of validation error
if (sonuc % 10 != tcArr[9].toInteger()) {
requestErrorMessageToTargetAPI = 'Please send a valid parameter: ' + variableToCheck + '.'
}
def tcToplam = 0
for (int i = 0; i < 10; i++) {
tcToplam += tcArr[i].toInteger()
}
// Create error message in case of validation error
if (tcToplam % 10 != tcArr[10].toInteger()) {
requestErrorMessageToTargetAPI = 'Please send a valid parameter: ' + variableToCheck + '.'
}
}
}
// Validate both Turkish ID numbers
validateTCKN(requestingUserIdentityCardNo)
validateTCKN(requestedIdentityCardNo)
Sample Request
{
"requestingUserIdentityCardNo": 11111111110,
"requestedIdentityCardNo": 11111111112
}
Explanation
This script performs the following operations:
- Parsing JSON: Parses the incoming request body using
JsonSlurper.
- Extracting Turkish ID Numbers: Extracts
requestingUserIdentityCardNo and requestedIdentityCardNo fields from JSON.
- Validation: For each Turkish ID number:
- Length check (must be 11 characters)
- Mathematical algorithm validation (checking 9th and 10th digits)
- Error Management: If validation fails, an error message is assigned to the
requestErrorMessageToTargetAPI variable and the request is not sent to the backend.
This script should be run on the request line (Request Policy) because it uses the requestBodyTextFromClient variable.