ServerSide Validation through validation object

This commit is contained in:
2019-01-23 21:43:27 +01:00
parent ecadd21228
commit 3e501b29d0
7 changed files with 58 additions and 7 deletions

View File

@ -10,11 +10,12 @@ namespace Vidly.Models
{
public int Id { get; set; }
[Required]
[Required(ErrorMessage ="Please enter customer's name.")]
[StringLength(255)]
public string Name { get; set; }
[Display(Name = "Date of Birth")]
[Min18YearsIfAMember]
public DateTime? BirthDate { get; set; }
public bool IsSubscribedToNewsLetter { get; set; }

View File

@ -14,5 +14,8 @@ namespace Vidly.Models
public short SignUpFee { get; set; }
public byte DurationInMonth { get; set; }
public byte DiscountRate { get; set; }
public static readonly byte Unknown = 0;
public static readonly byte PayAsYouGo = 1;
}
}

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Vidly.Models
{
public class Min18YearsIfAMember : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var customer = (Customer)validationContext.ObjectInstance;
if (customer.MembershipTypeId == MembershipType.Unknown ||
customer.MembershipTypeId == MembershipType.PayAsYouGo)
return ValidationResult.Success;
if (customer.BirthDate == null)
return new ValidationResult("Birthdate is required");
var age = DateTime.Today.Year - customer.BirthDate.Value.Year;
return (age > 18)
? ValidationResult.Success
: new ValidationResult("Customer should be at least 18 years old to go on a membership.");
}
}
}