Skip to content

Instantly share code, notes, and snippets.

@mostafabahri
Last active February 27, 2020 23:20
Show Gist options
  • Save mostafabahri/7c6daa293bac2afbcf763effa03b3dfc to your computer and use it in GitHub Desktop.
Save mostafabahri/7c6daa293bac2afbcf763effa03b3dfc to your computer and use it in GitHub Desktop.
pgSQL script to validate Iranian National ID format
-- AUTHOR: Mostafa
drop function if exists validate_national_id( text );
create or replace function validate_national_id(id text)
returns boolean as $$
declare
summation integer := 0;
arrayId text[] ;
rem integer;
lastElement integer;
begin
-- prepend zeros if missing
if length(id) = 8 then
id := '00' || id;
elseif length(id) = 9 then
id := '0' || id;
end if;
-- validate size
if length(id) != 10
then
return false;
end if;
-- cast code to array to iterate through
arrayId := regexp_split_to_array(id, '');
-- array index starts from 1 in postgres
for i in 1..9
loop
summation := summation + arrayId [i] :: integer * (11 - i);
end loop;
rem := summation % 11;
lastElement = arrayId [10] :: integer;
if rem < 2
then
return rem = lastElement;
end if;
return rem = 11 - lastElement;
exception when others then
return false;
end;
$$
language plpgsql;
select *
from validate_national_id('1111111111') valid2z,
validate_national_id('01e518672') valid1z,
validate_national_id('0018518672') valid,
validate_national_id('7731689951') as invalid,
validate_national_id('7731689956') as validAgain;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment