Hello Everybody

 

Based on this brilliant PHP class

https://www.phpclasses.org/package/5453-PHP-Validate-Saudi-resident-identifier-numbers.html

 

I searched the internet for PL/SQL code that achieves that but I didn't find. Here is another nice validator in multiple languages except PL/SQL.

https://github.com/alhazmy13/Saudi-ID-Validator

 

That is why I wrote, PL/SQL function to validate Saudi ID/Iqama/Residence number

CREATE OR REPLACE FUNCTION is_number (p_string IN VARCHAR2)
  RETURN INT
IS
  v_num NUMBER;
BEGIN
  v_num := TO_NUMBER(p_string);
  RETURN 1;
EXCEPTION
WHEN VALUE_ERROR THEN
  RETURN 0;
END is_number;
/

create or replace FUNCTION  "CHECKSTDID" (STDID in VARCHAR2) return number is  
  Result number; -- 1 --> Saudi , 2 --> Non-Saudi , 0 --> Invalid  
  ZF0dd  varchar2(100);  
  mysum    number := 0;  
  idtype varchar2(1);  
begin  
      
    -- If non-numeric then invalid  
    If ( is_number(STDID)=0 ) THEN  
       Result := 0;
       return Result;  
    END If;  
      
    --If length does not equal 10 then invalid  
    If(LENGTH(STDID) != 10) THEN  
       Result := 0;  
       return Result;  
    END IF;  
      
    -- get type  
    idtype := substr(STDID,1,1);  
      
    -- ID TYPE should be one or 2 only  
    --If length does not equal 10 then invalid  
    If(idtype not in ('1','2')) THEN  
       Result := 0;  
       return Result;  
    END IF;  
      
    -- you must do mapping between PHP's substr and PL/SQL's substr  
    for i in 0..9  
    loop  
      if ( Mod(i ,2) = 0 )then  
          ZF0dd := LPad( TO_NUMBER(substr(STDID,i+1,1))*2 , 2, '0');  
          mysum := mysum + TO_NUMBER(substr(ZF0dd,1,1)) + TO_NUMBER(substr(ZF0dd,2,1));       
      else  
          mysum := mysum + TO_NUMBER(substr(STDID, i+1 , 1 ));               
      end if;  
    end loop;  
      
    -- find result  
    if Mod(mysum,10) != 0 then  
      Result := 0;  
    else  
       Result := TO_NUMBER(idtype);  
    end if;  
      
    return(Result);  
end;  

 

I hope that helps someone

 

Regards

Mahmoud