.net - Convert algorithm to validate NIPC / NIF into a C# Regex (Regular Expression) -


i've got next simple algorithm validate nipc / nif identification portugal:

private bool isnipccorrect(string nifstring)     {         int controldigit = 0;          (int = 0; < nifstring.length - 1; i++)         {             controldigit += (int)char.getnumericvalue(nifstring[i]) * (10 - - 1);         };          controldigit = controldigit % 11;          if (controldigit <= 1)         {             controldigit = 0;         }         else         {             controldigit = 11 - controldigit;         }          if (controldigit == (int)char.getnumericvalue(nifstring[8]))         {             return true;         }         else         {             return false;         }     } 

i'd know if generate little regex validate identification in few lines.

initial validation:

  • lenght: 9 digits
  • control digit: nifstring[8]
  • how validate:

    1. sum = nifstring[7] * 2 + nifstring[6] * 3 + nifstring[5] * 4 + nifstring[4] * 5 + nifstring[3] * 6 + nifstring[2] * 7 + nifstring[1] * 8 + nifstring[0] * 9
      1. if(sum % 11 <= 1) controldigit = 0
      1. else controldigit = 11 - (sum % 11)
    2. then check if(controldigit == nifstring[8])

i've been thinking in next initial pattern = [0-9]{9}|\d{9}

but how use regex final validations too?

regards!

regex can't calculation suitable code check against first ^\d{9}$

you need make check before run rest of code if string not have 9 characters in error @ point nifstring[8]

so invalid nif of 12345 result in error rather return of false.


Comments

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -