Created
January 20, 2021 05:01
-
-
Save shubham-vunet/c474844f77d60d358d90eb2a9927a289 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; | |
using System; | |
using System.ComponentModel.DataAnnotations; | |
using System.Text.RegularExpressions; | |
namespace HBTU.Attributes | |
{ | |
public class Aadhar | |
{ | |
static readonly int[,] d = new int[,] | |
{ | |
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, | |
{1, 2, 3, 4, 0, 6, 7, 8, 9, 5}, | |
{2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, | |
{3, 4, 0, 1, 2, 8, 9, 5, 6, 7}, | |
{4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, | |
{5, 9, 8, 7, 6, 0, 4, 3, 2, 1}, | |
{6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, | |
{7, 6, 5, 9, 8, 2, 1, 0, 4, 3}, | |
{8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, | |
{9, 8, 7, 6, 5, 4, 3, 2, 1, 0} | |
}; | |
static readonly int[,] p = new int[,] | |
{ | |
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, | |
{1, 5, 7, 6, 2, 8, 3, 0, 9, 4}, | |
{5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, | |
{8, 9, 1, 6, 0, 4, 3, 5, 2, 7}, | |
{9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, | |
{4, 2, 8, 6, 5, 7, 3, 9, 0, 1}, | |
{2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, | |
{7, 0, 4, 6, 9, 1, 3, 2, 5, 8} | |
}; | |
static readonly int[] inv = { 0, 4, 3, 2, 1, 5, 6, 7, 8, 9 }; | |
public static bool ValidateVerhoeff(string num) | |
{ | |
int c = 0; int[] myArray = StringToReversedIntArray(num); | |
for (int i = 0; i < myArray.Length; i++) | |
{ | |
c = d[c, p[(i % 8), myArray[i]]]; | |
} | |
return c == 0; | |
} | |
public static bool ValidateAadharNumber(String aadharNumber) | |
{ | |
Regex regex = new Regex(@"^\d{4}\s?\d{4}\s?\d{4}$"); | |
Match match = regex.Match(aadharNumber); | |
return match.Success && ValidateVerhoeff(aadharNumber); | |
} | |
public static string GenerateVerhoeff(string num) | |
{ | |
int c = 0; int[] myArray = StringToReversedIntArray(num); | |
for (int i = 0; i < myArray.Length; i++) | |
{ | |
c = d[c, p[((i + 1) % 8), myArray[i]]]; | |
} | |
return inv[c].ToString(); | |
} | |
private static int[] StringToReversedIntArray(string num) | |
{ | |
int[] myArray = new int[num.Length]; | |
for (int i = 0; i < num.Length; i++) | |
{ | |
myArray[i] = int.Parse(num.Substring(i, 1)); | |
} | |
Array.Reverse(myArray); return myArray; | |
} | |
} | |
public class ValidateAadharAttribute : ValidationAttribute | |
{ | |
public ValidateAadharAttribute() | |
{ | |
} | |
protected override ValidationResult IsValid(object value, ValidationContext validationContext) | |
{ | |
if (!Aadhar.ValidateAadharNumber(((long)value).ToString())) | |
{ | |
return new ValidationResult("Invalid aadhar number."); | |
} | |
return ValidationResult.Success; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment