Question

I am creating a registration form. I have a property that is a national identity number. But I want the user to fill it after confirming the registration. Then I don't write it in the registration form.

commented:

National Identity Number
<div class="editor-field">
  @Html.EditorFor(model => model.IdentityNumber)
  @Html.ValidationMessageFor(model => model.IdentityNumber)
</div>

And this is my property:

[IdentityNumber("It is not a valid identity number")]
[Required(ErrorMessage = "You have to enter your national number")]
[DisplayName("National Identity Number:")]
public string IdentityNumber { get; set; }

But this doesn't work. I think the reason is the attributes [IdentityNumber] and [Required]. If I comment them,

public ActionResult Register(Member model)
{
    if (ModelState.IsValid)
    {
        //.....

ModelState.IsValid is false. If I uncomment them, it returns true. So where must I change something to allow it? I mean, I want the user to write his/her identity number, after registration.

In my db, the identity national number field allows null also.

Edit: Here is my attribute code:

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property,
AllowMultiple = false, Inherited = true)]
public class IdentityNumberAttribute : ValidationAttribute, IClientValidatable
{
    private string WrongIdentityNumber;

    public IdentityNumberAttribute(string message)
        :base("Invalid an identity number")
    {
        WrongIdentityNumber = message;
    }

    private string identityNumber;
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value == null)
            return new ValidationResult(WrongIdentityNumber);   

        identityNumber = value.ToString();

        if (identityNumber.Length != 11)
            return new ValidationResult(WrongIdentityNumber);

        int sum = 0;

        for (int i = 0; i < identityNumber.Length - 1; i++)
        {
            sum += Convert.ToInt32(identityNumber[i].ToString());
        }

        return sum.ToString()[1] == identityNumber[10]
                   ? ValidationResult.Success
                   : new ValidationResult(WrongIdentityNumber);
    }


    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        ModelClientValidationRule validationRule = new ModelClientValidationRule();
        validationRule.ValidationType = "identitynumber";
        validationRule.ErrorMessage = "Invalid identity number";
        validationRule.ValidationParameters.Add("param", "");
        return new List<ModelClientValidationRule> { validationRule };

        //var rule = new ModelClientValidationRule();
        //rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
        //rule.ValidationParameters.Add("identitynumber", identityNumber);     //küçük harfle yaz html kuralı
        //rule.ValidationType = "identitynumber";
        //yield return rule;
     }
}
Was it helpful?

Solution

You could add this line

ModelState.Remove("ErrorKey");//you can find the error key by stepping though your code
if (ModelState.IsValid)
        {
          .....

the "ErrorKey" will be something like "YourModelName.YourPropertyName". Set a breakpoint and hover over ModelState and you can see all the keys.

But you should create a view model that has only the properties you need, put your data annotations on there, and leave your domain models out of it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top