Skip to content

Instantly share code, notes, and snippets.

@MSHADroo
Last active May 22, 2019 11:50
Show Gist options
  • Save MSHADroo/671af7706003b63a40b3906707bef1a2 to your computer and use it in GitHub Desktop.
Save MSHADroo/671af7706003b63a40b3906707bef1a2 to your computer and use it in GitHub Desktop.
Mysql function: validate Iran national code
DELIMITER $$
CREATE FUNCTION CHECK_NATIONAL_CODE(national_code VARCHAR(50))
RETURNS BOOLEAN
DETERMINISTIC
BEGIN
DECLARE c INT;
DECLARE n INT;
DECLARE r INT;
IF length(national_code) != 10
THEN
RETURN FALSE;
END IF;
IF national_code REGEXP '^[0-9]'
THEN
IF (national_code = '1111111111' OR
national_code = '0000000000' OR
national_code = '2222222222' OR
national_code = '3333333333' OR
national_code = '4444444444' OR
national_code = '5555555555' OR
national_code = '6666666666' OR
national_code = '7777777777' OR
national_code = '8888888888' OR
national_code = '9999999999')
THEN
RETURN FALSE;
END IF;
SET c = FLOOR(substr(national_code, 10, 1));
SET n = FLOOR(substr(national_code, 1, 1)) * 10 +
FLOOR(substr(national_code, 2, 1)) * 9 +
FLOOR(substr(national_code, 3, 1)) * 8 +
FLOOR(substr(national_code, 4, 1)) * 7 +
FLOOR(substr(national_code, 5, 1)) * 6 +
FLOOR(substr(national_code, 6, 1)) * 5 +
FLOOR(substr(national_code, 7, 1)) * 4 +
FLOOR(substr(national_code, 8, 1)) * 3 +
FLOOR(substr(national_code, 9, 1)) * 2;
SET r = n - (FLOOR((n / 11)) * 11);
IF ((r = 0 AND r = c) OR (r = 1 AND c = 1) OR (r > 1 AND c = (11 - r)))
THEN
RETURN TRUE;
ELSE
RETURN FALSE;
END IF;
ELSE
RETURN FALSE;
END IF;
END $$
DELIMITER ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment