0

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://learn.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.

w0051977
  • 15,099
  • 32
  • 152
  • 329

1 Answers1

0

You could use this constructor and check if it gives you an 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
}

Although the method you mentioned should also work just fine. Except that this doesn't need to care about regionalization.

Oh and if you use Xamarin.Forms you could take a look at Behaviors so that you can avoid copypasting your validation logic. Even the example there is a validating one.

iSpain17
  • 2,502
  • 3
  • 17
  • 26
  • I thought of that. However, is it advisable to throw an exception in this case? – w0051977 Aug 09 '19 at 13:13
  • Well, that depends on your needs. But since you want to validate data, it is possible the date will not be valid, so in my opinion, no need to throw anything. You need to notify the user that their input was not good. – iSpain17 Aug 09 '19 at 13:25
  • So you would use the code I posted in my question? Thanks. – w0051977 Aug 09 '19 at 13:42
  • No. I would use this one, as this does not need to take into account regionalization. – iSpain17 Aug 09 '19 at 13:48