Search code examples
asp.net-coreattributesvalidationattribute

How to create custom validation attribute for Iranian national code in asp.net core?


I'm trying to validate the national code in asp.net core. I found the validation code and it works when I use it as a method but I want to create it as an validation attribute.This is my code in attribute class:

public class ValidateNationalCodeAttribute : ValidationAttribute
{        
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        string nationalCode = value.ToString();
      
        var isValid = true;

        char[] chArray = nationalCode.ToCharArray();
        int[] numArray = new int[chArray.Length];
        for (int i = 0; i < chArray.Length; i++)
        {
            numArray[i] = (int)char.GetNumericValue(chArray[i]);
        }
        int num2 = numArray[9];
        int num3 = ((((((((numArray[0] * 10) + (numArray[1] * 9)) + (numArray[2] * 8)) + (numArray[3] 
      * 7)) + (numArray[4] * 6)) + (numArray[5] * 5)) + (numArray[6] * 4)) + (numArray[7] * 3)) + 
         (numArray[8] * 2);
        int num4 = num3 - ((num3 / 11) * 11);
        if ((((num4 == 0) && (num2 == num4)) || ((num4 == 1) && (num2 == 1))) || ((num4 > 1) && (num2 
        == Math.Abs((int)(num4 - 11)))))
        {
            isValid = true;
        }
        else
        {
            isValid = false;
        }
        switch (nationalCode)
        {
            case "0000000000":
            case "1111111111":
            case "22222222222":
            case "33333333333":
            case "4444444444":
            case "5555555555":
            case "6666666666":
            case "7777777777":
            case "8888888888":
            case "9999999999":
                isValid = false;
                break;
        }


        if (!isValid)
        {
            return new ValidationResult("invalid");
        }
        return ValidationResult.Success;
    }
}

This is how I used it. It's in a viewModel class:

    [ValidateNationalCode]
    public string NationalCode { get; set; }

I run the app and for example I enter 1111111111 for national code but it doesn't show any error. What should I do?

EDIT: This is the view:

 <div class="col-md-4 form-group">
                    <label asp-for="NationalCode" class="required"></label>
                    <input class="form-control text-box single-line valid" 
        asp-for="NationalCode">
                    <span asp-validation-for="NationalCode" class="text- 
       danger"></span>
                </div>

      

This is the controller:

    [HttpPost("{id}")]
    public async Task<IActionResult> installment(long id, NewInstallmentGVM 
        model)
    {           
        if (ModelState.IsValid)
        {
            var Result = await 
         _installmentService.AddInstallmentFromPayment(id, model);
            if (Result.Succeeded)
            {

                return View("InstallmentSucceeded",Result.Value);
            }
            else
            {
                return View("InvalidInstallment");
            }
        }
        return View(model);
    }

Solution

  • As far as I know, the client validation is not as same as the server validation. I guess you want to show the error message on the client side. But this is not the same thing.

    Asp.net core doesn't support customer attribute validate error message to show in the client side.

    If you want to do this, you should write it by yoursefl.

    More details, you could refer to this article.