Я хотел бы создать свой собственный валидатор, который проверяет правильность PESEL в регистрационной форме.
Критерии:
- The field can not be empty if it is an error.
- The numeric value is to be 11 numbers long, otherwise an error.
- If the validation function does not check the PESEL calculation method, it returns an error.
Принцип расчета PESEL:
In 3 simple steps we will describe below how to calculate the check digit in the PESEL number. As an example, we will use the number 0207080362.
Multiply each digit from the PESEL number by the appropriate weight: 1-3-7-9-1-3-7-9-1-3. 0 * 1 = 0 2 * 3 = 6 0 * 7 = 0 7 * 9 = 63 0 * 1 = 0 8 * 3 = 24 0 * 7 = 0 3 * 9 = 27 6 * 1 = 6 2 * 3 = 6
Add the obtained results to yourself. Note that if you receive a two-digit number during the multiplication process, add only the last digit (for example, instead of 63, add 3). 0 + 6 + 0 + 3 + 0 + 4 + 0 + 7 +6 + 6 = 32 Subtract the result from 10. Note: if you receive a two-digit number during the addition, subtract only the last digit (for example, instead of 32, subtract 2). The digit you get is a check digit. 10 - 2 = 8 full PESEL number: 02070803628
Практически у меня это не работает, я всегда говорю что-то вроде этого в своей форме:
Что случилось ?
Введите с пустым значением:
введите описание изображения здесь
введите описание изображения здесь
введите описание изображения здесь
Код:
public class ValidatePesel : ValidationAttribute
{
int result_status = 0;
public string errorLenght = "Długość numeru PESEL musi zawierać 11 cyfr";
public string errorPesel = "numer PESEL jest niepoprawny";
public string errorType = "Podana wartość nie jest numerem PESEL";
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string pesel = value.ToString();
bool result_pesel = int.TryParse(pesel, out result_status);
// Verification of PESEL correctness
if (result_pesel)
{
if (pesel.Length == 11) // Check if the given length is correct
{
int[] weight = { 1, 3, 7, 9, 1, 3, 7, 9, 1, 3 }; // weights to calculate
int sum = 0;
int controlNum = int.Parse(pesel.Substring(10, 11)); // to the control value we assign the last number, the first one is the last one is 11 because 10 is the number 11 and then the length of the data
for (int i = 0; i < weight.Length; i++)
{
sum += int.Parse(pesel.Substring(i, i + 1)) * weight[i]; // we multiply each number by weight
}
sum = sum % 10; // we return the value of the checksum
if (10 - sum == controlNum)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult(errorPesel);
}
}
else
return new ValidationResult(errorLenght);
}
else
return new ValidationResult(errorType);
}
}
код, реализованный в модели:
namespace Clinic. Models
{
public class RegistrationForPatient: ValidatePesel
{
public int Id {get; set; }
// We create validation of user data, if the user leaves an empty field, it returns a message from the RequiredAttribute function
[Required]
[ValidatePesel]
[Display (Name = "Pesel")]
public string PESEL {get; set; }
// Email validation, required field
[Required]
[Display (Name = "E-mail")]
[EmailAddress]
public string Email {get; set; }
[Required (ErrorMessage = "Password field, can not be empty")]
[Display (Name = "Password")]
public string Password {get; set; }
[Required (ErrorMessage = "Please repeat the password")]
[Display (Name = "Repeat password")]
public string RepeatPassword {get; set; }
}
}





Несколько ошибок с вашей стороны:
и рабочий код:
public class ValidatePesel : ValidationAttribute
{
public string errorLenght = "Długość numeru PESEL musi zawierać 11 cyfr";
public string errorPesel = "numer PESEL jest niepoprawny";
public string errorType = "Podana wartość nie jest numerem PESEL";
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string pesel = value.ToString();
if (!decimal.TryParse(pesel, out decimal result_status)) return new ValidationResult(errorType);
if (pesel.Length == 11)
{
int[] weight = { 1, 3, 7, 9, 1, 3, 7, 9, 1, 3 };
int sum = 0;
int controlNum = int.Parse(pesel.Substring(10, 1));
for (int i = 0; i < weight.Length; i++)
{
sum += int.Parse(pesel.Substring(i, 1)) * weight[i];
}
sum = sum % 10;
if (10 - sum == controlNum) return ValidationResult.Success;
else return new ValidationResult(errorPesel);
}
else return new ValidationResult(errorLenght);
}
}