次のメソッドがあり、実際の無効/有効な日付を処理する限り正しく機能しますが、空の文字列または のようなマスク付きの日付に遭遇した場合__/__/____
、それらを有効なものとして渡したいのですが、それらをDateTime.TryParse
無効にします。以下のメソッドを変更して、無効なシナリオを渡すにはどうすればよいですか? 次のメソッドの下には、プログラムの例があります。
public bool ValidateDate(string date, out string message)
{
bool success = true;
message = string.Empty;
DateTime dateTime;
if(DateTime.TryParse(date,out dateTime))
{
success = false;
message = "Date is Invalid";
}
return success;
}
void Main()
{
//The only date below that should return false is date4.
string date = "01/01/2020";
string date2 = "";
string date3 = "__/__/____";
string date4 = "44/__/2013";
string message;
ValidateDate(date, out message); //Should return true
ValidateDate(date2, out message); //Should return true
ValidateDate(date3, out message); //Should return true
ValidateDate(date4, out message); //Should return false
}
if(!DateTime.TryParse(date3,out dateTime))
検証したい日付に対して false が返されるため、変更できません。
のようなことも試しましif(!date3.contains("_") && DateTime.TryParse(date3,out dateTime))
たが、それでも失敗します。検証の順序を反転する必要がありますか? 問題は、最初の無効な日付で false を返すだけでなくStringBuilder
、すべての無効な日付を作成してから返すことです。
if(DateTime.TryParse(date3,out dateTime))
return true;
else
return true;
public bool ValidateDate(string date, out string message)
{
string[] overrides = {"","__/__/____"};
bool success = true;
message = string.Empty;
DateTime dateTime;
if(!overrides.Contains(date) && !DateTime.TryParse(date,out dateTime))
{
success = false;
message = "Date is Invalid";
}
return success;
}