我问的是SchoolYear
。
就像这个例子
2013-2014 (StartYear-EndYear)
如何验证用户是否实际进入学年(例如2013-2014
)
这是我到目前为止所尝试过的。
private void TextBox_Validating(object sender, CancelEventArgs e)
{
if (!string.IsNullOrWhiteSpace(studentLastSchoolAttendedSchoolYearTextBox.Text))
{
int fromYear = 0;
int toYear = 0;
string[] years = Regex.Split(studentLastSchoolAttendedSchoolYearTextBox.Text, @"-");
fromYear = int.Parse(years.FirstOrDefault().ToString());
if (fromYear.ToString().Length == 4)
{
if (years.Count() > 1)
{
if (!string.IsNullOrWhiteSpace(years.LastOrDefault()))
{
toYear = int.Parse(years.LastOrDefault().ToString());
if (fromYear >= toYear)
{
e.Cancel = true;
MessageBox.Show("The 'From Year' must be lesser than to 'To Year'.\n\nJust leave as a empty to avoid validating.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
else
{
e.Cancel = true;
MessageBox.Show("Please enter a valid School range Year format.\nEx.: 2010-2011\n\nJust leave as empty to avoid validating.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
else
{
studentLastSchoolAttendedSchoolYearTextBox.Text = fromYear.ToString() + "-" + Convert.ToInt32(fromYear + 1).ToString();
}
}
else
{
e.Cancel = true;
MessageBox.Show("Please enter a valid School range Year format.\nEx.: 2010-2011\n\nJust leave as empty to avoid validating.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
答案 0 :(得分:2)
假设2013-2014
是有效格式,这可能是一个有效的函数:
public static bool IsSchoolYearFormat(string format, int minYear, int maxYear)
{
string[] parts = format.Trim().Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 2)
{
int fromYear; int toYear;
if (int.TryParse(parts[0], out fromYear) && int.TryParse(parts[1], out toYear))
{
if (fromYear >= minYear && toYear <= maxYear && fromYear + 1 == toYear)
return true;
}
}
return false;
}
答案 1 :(得分:1)
public bool IsSchoolYearFormat(string toCheck)
{
string[] arr = toCheck.Trim().Split('-'); //splits the string, eg 2013-2014 goes to 2013 and 2014
if (arr.Length != 2) //if there is less or more than two school years it is invalid.
{
return false;
}
int one, two;
if (!int.TryParse(arr[0], out one))
{
return false;
}
if (!int.TryParse(arr[1], out two))
{
return false;
}
//if they don't parse then they are invalid.
return two - 1 == one && two > 1900 && one > 1900; //to please AbZy
//school year must be in the format yeara-(yeara+1)
}