the title looks a bit weird sorry for it.
Well I am new in Asp.net MVC 3. I want to create an attribute for my one property which name is national identity number.
public class IdentityNumberControl : ActionFilterAttribute
{
public string WrongIdentityNumber { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if(??? )
{
filterContext.HttpContext.Response.Write(WrongIdentityNumber);
return;
}
base.OnActionExecuting(filterContext);
}
}
my member class is here
public class Member
{
public int ID { get; set; }
[Required(ErrorMessage = "You have to enter your name")]
[StringLength(50, ErrorMessage ="Your name length can not be less than{2} more than {1} ", MinimumLength = 3)]
[Display("Name :")]
public string Name { get; set; }
[Required(ErrorMessage = "You have to enter your surname")]
[StringLength(40, ErrorMessage = "Your surname length can not be less than{2} more than {1} ", MinimumLength = 2)]
[Display("Surname :")]
public string SurName { get; set; }
[Required(ErrorMessage = "You have to enter your password")]
[StringLength(20, ErrorMessage = "Your name lengt can not be less than{2} more than {1} ", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display("Password :")]
public string Password { get; set; }
public string PasswordSalt { get; set; }
[IdentityNumberControl(WrongIdentityNumber = "It is not a valid identity number")]
public double IdentityNumber { get; set; }
}
so I want to check identitynumber is true or not (I have a calculation method to confirm it) I know that I must write code in IdentityNumberControl class. But I dont know how to get value of identitynumber in OnActionExecuting method.
I hope I explain my issue
here is my solution
public class IdentityNumberAttribute : ValidationAttribute
{
private string WrongIdentityNumber;
public IdentityNumberAttribute(string message)
{
WrongIdentityNumber = message;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string 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);
}
}
it calculates that if valid turkish natioanal identity number or not
you can use this attirbute like that
[IdentityNumber("It is not a valid identity number")]
[Required(ErrorMessage = "You have to enter your identity number")]
[DisplayName("National Identity Number:")]
public string IdentityNumber { get; set; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.