I have 3 properties for a custom class, its Date, Hour and Minute. These represent fields the user can enter, but they are not required, but if one field is filled in then the other 2 should as well (Not sure that part is possible with pure c#)
I have made this code
[RegularExpression("[0-9]{2}-[0-9]{2}-[0-9]{4}", ErrorMessage = "Date should be in the following format: dd-mm-yyyy")]
[MaxLength(10)]
public string Date { get; set; }
[CustomRange(0, 24, ErrorMessage = "Hour must be between 00 and 24")]
public string Hour { get; set; }
[CustomRange(0, 59, ErrorMessage = "Hour must be between 00 and 59")]
public string Minute { get; set; }
.
public class CustomRangeAttribute : ValidationAttribute
{
public int Min { get; set; }
public int Max { get; set; }
public CustomRangeAttribute(int min, int max)
{
Min = min;
Max = max;
}
public override bool IsValid(object value)
{
var stringValue = Convert.ToString(value, CultureInfo.CurrentCulture);
int tmp;
if(int.TryParse(stringValue, out tmp))
{
return tmp >= Min && tmp <= Max;
}
return false;
}
}
The date part works fine, that one is optional, but the hour and minute it complains about as if they had [Required], so is that possible to make them optional as well?
I changed so I used regular expressions instead
[RegularExpression("[0-9]{2}-[0-9]{2}-[0-9]{4}", ErrorMessage = "Date should be in the following format: dd-mm-yyyy")]
[MaxLength(10)]
public string Date { get; set; }
[RegularExpression("[0-1]{1}[0-9]{1}|[2]{1}[0-3]{1}")]
public string Hour { get; set; }
[RegularExpression("[0-5]{1}[0-9]{1}")]
public string Minute { get; set; }