首页 > 解决方案 > Validating a three field date for an Xamarin application that targets an Android device

问题描述

Say I have a date value contained within three fields:

Day
Month
Year

How would I validate this in an Xamarin app? I have read plenty of similar questions on here like this one: How to validate date input in 3 fields?. However, most appear to assume you are developing a website and can use JavaScript for this.

The ones that do show server side code advise using DateTime.TryParse (https://docs.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=netframework-4.8). Is this the most appropriate option? The reason I ask is because:

1) DateTime.TryParse expects one parameter for the date instead of three
2) I have read other questions on here that advise again it because of regionalisation issues without really explaining why.

Is this still the most suitable way to do it - taken from here: validate 3 textfields representing date of birth:

DateTime D;
string CombinedDate=String.Format("{0}-{1}-{2}", YearField.Text, MonthField.Text, DayField.Text);
if(DateTime.TryParseExact(CombinedDate, "yyyy-M-d", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out D)) {
  // valid
} else {
  // not valid
}

The code above was written in 2009. I remember reading another question on an Xamarin forum, which said that this is inelegant these days. Hence the reason for the question. Unfortunately I cannot now find this question to link to it.

标签: c#xamarin

解决方案


您可以使用构造函数并检查它是否为您提供ArgumentOutOfRangeException

int year = int.Parse(YearField.Text);
int month = int.Parse(MonthField.Text);
int day = int.Parse(DayField.Text);

try {
    DateTime date = new DateTime(year, month, day);
catch (ArgumentOutOfRangeException) {
    //Date is invalid
}

尽管您提到的方法也应该可以正常工作。除了这不需要关心区域化。

哦,如果你使用 Xamarin.Forms,你可以看看Behaviors,这样你就可以避免复制粘贴你的验证逻辑。即使是示例也有一个验证示例。


推荐阅读