PPS Number Validation iOS Swift

180 views Asked by At

PPS number majorly used in Ireland. Its validation contains more calculation. How can we validate the PPS number in swift code?.

1

There are 1 answers

0
Abishek Thangaraj On BEST ANSWER

Below code is used to validate the PPS number in iOS Swift

  func isValidPPSN(_ ppsn: String) -> Bool {
    let ppsnRegEx = "^([0-9]{7})([A-Z]{1,2})$"
    let ppsnPred = NSPredicate(format:"SELF MATCHES %@", ppsnRegEx)
    return ppsnPred.evaluate(with: ppsn)
  }
  
  func validatePPSN(objInputValue: String) -> Bool {
    
    if !(isValidPPSN(objInputValue)) {
      return false
    }
    else {
      let numericPart = objInputValue[0 ..< 7]
      let checksumCharacter = objInputValue[numericPart.count ..< objInputValue.count]
      
      var multiplyingFactor = 8
      var sum = 0
      
      for i in numericPart {
        sum += (Int(String(i)) ?? 0) * multiplyingFactor
        multiplyingFactor -= 1
      }
      
      if checksumCharacter.count == 2 {
        sum += (Int(Character(checksumCharacter[1].uppercased()).asciiValue ?? 0) - 64) * 9
      }else{
        return false
      }
      
      let checksum = sum % 23;
      let asciiValue = Character(checksumCharacter[0].uppercased()).asciiValue ?? 0
      if ((checksum + 64) == asciiValue || (checksum == 0 && asciiValue == 87)) {
        return true
      } else {
        return false
      }
    }
  }
  

Call the function validatePPSN(objInputValue: String) pass PPS number in parameter its returns bool value number is valid or Not.