Skip to content

Instantly share code, notes, and snippets.

@diogoalexsmachado
Last active July 16, 2018 14:06
Show Gist options
  • Save diogoalexsmachado/b3f4c916bf7e58dca73c1cd67415cbbb to your computer and use it in GitHub Desktop.
Save diogoalexsmachado/b3f4c916bf7e58dca73c1cd67415cbbb to your computer and use it in GitHub Desktop.
public class NISSValidator {
private NISSValidator() {
}
/**
* Validates if a given string niss is valid.
*
* @param niss number to validate
* @return true if the input is valid and false otherwise
*/
public static boolean isValid(String niss) {
return hasValidLength(niss) &&
isNumeric(niss) &&
hasValidFirstDigit(niss) &&
hasValidControlDigit(niss);
}
private static boolean hasValidLength(String niss) {
return !(niss == null || niss.length() != 11);
}
private static boolean isNumeric(String str) {
for (char c : str.toCharArray()) {
if (!Character.isDigit(c)) {
return false;
}
}
return true;
}
private static boolean hasValidFirstDigit(String niss) {
return niss.charAt(0) == '1' || niss.charAt(0) == '2';
}
/**
* Validates the niss intigrity.
* Sums all the niss digits multiplied by factors array.
* The niss is valid if 9 minus the reminder of the division
* of niss factors by 10 is equal to the niss check digit.
*
* @param niss digits to validate
* @return true if the control digit is valid and false otherwise.
*/
private static boolean hasValidControlDigit(String niss) {
int[] nissArray = convertToIntegerArray(niss);
final int[] FACTORS = {29, 23, 19, 17, 13, 11, 7, 5, 3, 2};
int sum = 0;
for (int i = 0; i < FACTORS.length; i++) {
sum += nissArray[i] * FACTORS[i];
}
return nissArray[nissArray.length - 1] == (9 - (sum % 10));
}
private static int[] convertToIntegerArray(String niss) {
final int[] ints = new int[niss.length()];
for (int i = 0; i < niss.length(); i++) {
ints[i] = Integer.parseInt(String.valueOf(niss.charAt(i)));
}
return ints;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment