Custom Validation MVC 5

2019-09-15 19:25发布

问题:

Ok i have this Edit form, what i need is some kind of custom validation for when i enter ReturnDate it Shouldn't be lower then the date of IssueDeadLineDate value. Can i do with Some kind of custom validation or what do i need ?

Edit View Picture

  namespace Library.Models
 {
  public class BookStatusView
  {
    public int Id { get; set; }
    public string UserId { get; set; }
    public DateTime IssueDeadlineDate { get; set; }
    public DateTime ReturnDeadlineDate { get; set; }

    public DateTime? ReturnDate { get; set; }
    public int BookId { get; set; }
    public string AspNetUser { get; set; }
    public string BookName { get; set; }


    public IEnumerable<SelectListItem> qwerty { get; set; }

    public string Email { get; set; }
    public string FirstName { get; set; }

This is my BookStatusView model where i want to implement custom validation. If u need any other code feel free to ask i will paste it ass soon as i see it.

回答1:

if you are looking to do server side validation you can do a simple comparison

if(ReturnDate < IssueDeadlineDate) in the controller

if you are wanting client side validation you will need to compare the model values in a similar way but in javascript

You could also try using a custom ValidationAttribute

http://dotnetmentors.com/mvc/how-to-do-custom-validation-using-validationattribute-of-aspnet-mvc.aspx