2
我有一個自定義的類,它的日期,小時和分鐘3個屬性。這些代表域用戶可以進入,但它們不是必需的,但如果一個字段填入那麼其他2也應如此(不知道這部分是可能的純C#)如何允許什麼或在asp.net MVC3一個屬性一定值
我有此代碼
[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;
}
}
的日期部分工作正常,一個是可選的,但小時和分鐘就抱怨,就好像他們有[必填],所以是有可能讓他們選購呢?
我改變了,所以我用正則表達式,而不是
[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; }