c# - 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.
解决方案
您可以使用此构造函数并检查它是否为您提供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,这样你就可以避免复制粘贴你的验证逻辑。即使是示例也有一个验证示例。
推荐阅读
- c++ - 有没有办法检查 2 个聚合是否相等?
- javascript - 加载页面后正确的动画方法?
- python - Pytorch Tensor 如何获取元素的索引?
- python - 运行python程序时输入抛出错误
- node.js - Jest 没有正确退出
- c - 在进行 64 位无符号整数除法时如何管理 65 位分配?
- php - 为什么 Doctrine SQLite 会忽略身份验证配置?
- javascript - 我想问是否有任何方法可以为每条新记录获取标签.. 像出现在 gmail 中的新标签
- java - 在 Firestore 中显示用户的照片
- javascript - Javascript在点击时隐藏/显示不起作用