User.cs (Modelimiz)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
public class User { [Required] [StringLength(20,ErrorMessage ="Adınız en fazla 20 karakter olabilir",MinimumLength =3)] public string Firstname { get; set; } [Required] [StringLength(20, ErrorMessage = "Soyadınız en fazla 20 karakter olabilir", MinimumLength = 3)] public string Lastname { get; set; } [Required] [EmailAddress] public string Email { get; set; } [Required] [StringLength(15, ErrorMessage = "Şifreniz en fazla 15 en az 6 karakter olabilir", MinimumLength = 6)] public string Password { get; set; } [Required] [Compare("Password",ErrorMessage ="Şifre bilgileriniz kontrol ediniz")] public string ConfirmPassword { get; set; } [Required] [Range(18,100,ErrorMessage ="Yaş aralığı 18-100 arası olmalıdır")] public int BirthYear { get; set; } [CreditCard] public string CreditCard { get; set; } [Url] public string FacebookProfileUrl { get; set; } [Required] [Phone] public string Phone { get; set; } } |
ValidationController (modelimizi dolduruyoruz)
1 2 3 4 5 6 |
[HttpPost] [ModelValidation] public HttpResponseMessage Insert(User user) { return Request.CreateResponse(HttpStatusCode.OK, "Kullanıcı oluşturuldu"); } |
ModelValidation.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class ModelValidation : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) //action çalışmadan önce çalışır { if (actionContext.ModelState.IsValid) { base.OnActionExecuting(actionContext); } else { var errorList = actionContext.ModelState.Values.SelectMany(v => v.Errors).Select(x => x.ErrorMessage).ToList(); var errorMessage = string.Join(Environment.NewLine, errorList); actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, errorMessage); } } } |