Мой валидатор не соответствует требованиям, возвращает не правильное значение

Я хотел бы создать свой собственный валидатор, который проверяет правильность PESEL в регистрационной форме.

Критерии:

  1. The field can not be empty if it is an error.
  2. The numeric value is to be 11 numbers long, otherwise an error.
  3. 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

Практически у меня это не работает, я всегда говорю что-то вроде этого в своей форме:

Что случилось ?

Введите с пустым значением:

введите описание изображения здесь

  1. Введите неправильное число:

введите описание изображения здесь

  1. Введите правильный номер:

введите описание изображения здесь

Код:

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; }
     }
}
Стоит ли изучать PHP в 2026-2027 годах?
Стоит ли изучать PHP в 2026-2027 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
1
0
156
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Несколько ошибок с вашей стороны:

  • максимальное значение int равно 2 147 483 647 - 10 цифр, вам нужно 11
  • подстрока из 1 символа, а не 11 или i+1

и рабочий код:

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);
    }
}

Другие вопросы по теме