1

I`m new On Asp.net Mvc (4)

can I call a function to validate a model property ( It is more than REQUIRED , MAXLENGHT...)

e.g:

public class Movie 

{

   public int ID { get; set; }

   [Required]
   public string Title { get; set; }

   [DataType(DataType.Date)]
   public DateTime ReleaseDate { get; set; }

   [Required]
   public string Genre { get; set; }

   [Range(1, 100)]
   [DataType(DataType.Currency)]
   public decimal Price { get; set; }

   [StringLength(5)]
   public string Rating { get; set; }
   [***Call some function here***]

   public string blabla{get;set;}
}

Or maybe another idea?

2
  • what's your question? you can use ModelState.IsValid in your controller. here is good explanation. Commented Dec 30, 2014 at 8:11
  • @Nima Ghaferi, You can use remote validation Commented Dec 30, 2014 at 9:02

1 Answer 1

2

This can be done by imlementing a custom validation attribute check this link and this

Example:

public sealed class DateEndAttribute : ValidationAttribute
{
    public string DateStart { get; set; }

    public override bool IsValid(object value)
    {
        // Get value of datestart property
        string dateStartString = HttpContext.Current.Request[DateStart];
        DateTime dateEnd = (DateTime)value;
        DateTime dateStart = DateTime.Parse(dateStartString);

        // Start must be before end
        return dateStart <= dateEnd;
    }

    public override string FormatErrorMessage(string name)
    {
        return name + " has to be after startdate";
    }
}

Usage:

    [Required]
    [Display(Name = "StartDate")]
    public DateTime StartDate { get; set; }

    [Display(Name = "EndDate")]
    [DateEnd(DateStart = "StartDate")]
    public DateTime EndDate { get; set; }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.