Skip to content
Loading
  • Gautam Parmar
    0
    let's say,In validation we want the end date to be today's date instead of anyhardcode value. To achieve this we would be use
     
    DateTime.Now.ToShortDateString() as shown below.
    1. [Range(typeof(DateTime), "01/01/2015", DateTime.Now.ToShortDateString())]  
    2. [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]  
    3. public DateTime HireDate { get; set; }  
    At this point, if you compile, you will get an error - An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type.
     
    To fix this, we can create a custom DateRangeAttribute. Here is the code.
     
    Copy and paste the following code in DateRangeAttribute.cs class file.
    1. public class DateRangeAttribute : RangeAttribute  
    2. {  
    3. public DateRangeAttribute(string minimumValue)  
    4. : base(typeof(DateTime), minimumValue,  
    5. DateTime.Now.ToShortDateString())  
    6. {  
    7. }  
    8. }  
    Finally decorate "Joining Date" property with our custom DateRangeAttribute as shown below.
    1. [DateRange("01/01/2015")]  
    2. [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]  
    3. public DateTime Dateofjoining{ get; set; }  
    0
  • Hamid Khan
    0
    I think interviewer do not want to use data annotation,
     
    in this scenario you need to add your own validation class, and implement your logic under this class method:
     
    but if you think for data annotation : then go for details:
     
    ValidationAttribute class is included in DataAnnotations namespace. It helps you to validate model data received from user. It gives you many in built validation attributes like StringLength, Required, DataType for validating model.
     
    http://dotnetmentors.com/mvc/how-to-do-custom-validation-using-validationattribute-of-aspnet-mvc.aspx
    0
  • 0
    Dear frnds This is fine thanks for the update.here I want chechbox using custom validation
    0