Any suggestions on cleaning up this code:
public override bool Validate(Control control, object value)
{
bool res = false;
string str = string.Empty;
try
{
if (((string)value).Length > 0)
str = value.ToString();
}
catch (Exception e)
{
res = false;
this.ErrorText = "Bad values " + e.Message;
this.ErrorType = ErrorType.Critical;
}
//Is it empty?
if (String.IsNullOrEmpty(str))
{
res = false;
this.ErrorType = ErrorType.Critical;
}
Regex RegNrShortRegexDarm = new Regex(@"([F][A][D][-][Z]\d{3})");
Regex RegNrLongRegexDarm = new Regex(@"([F][A][D][-][Z]\d{3}[-][0-9]+$)");
Regex RegNrShortRegexBrust = new Regex(@"([F][A][B][-][Z]\d{3})");
Regex RegNrLongRegexBrust = new Regex(@"([F][A][B][-][Z]\d{3}[-][0-9]+$)");
if (selectedItem == Constants.Item1)
{
this.ErrorText = "The correct form is: FAD-Zxxx oder FAD-Zxxx-x !";
//has the form FAD-Zxxx
if (RegNrShortRegexDarm.IsMatch(str) && str.Length == 8)
{
// Number is valid
res = true;
}
//has the form FAD-Zxxx-x
if (RegNrLongRegexDarm.IsMatch(str) && str.Length >= 10 && str.Length <= 12)
{
// Number is valid
res = true;
}
}
else if (selectedItem == Constants.Item2)
{
this.ErrorText = "The correct form is: FAB-Zxxx oder FAB-Zxxx-x !";
//has the form FAB-Zxxx
if (RegNrShortRegexBrust.IsMatch(str) && str.Length == 8)
{
// Number is valid
res = true;
}
//has the form FAB-Zxxx-x
if (RegNrLongRegexBrust.IsMatch(str) && str.Length >= 10 && str.Length <= 12)
{
// Number is valid
res = true;
}
}
return res;
}
Later Edit:
I've reached the following solution:
public override bool Validate(Control control, object value)
{
var str = value as string;
var letter = (selectedItem == Constants.Item1) ? "D" : "B";
var errText = String.Format("The correct form is: FA{0}-Zxxx or FA{0}-Zxxx-x !", letter);
if (string.IsNullOrWhiteSpace(str))
{
this.ErrorType = ErrorType.Critical;
this.ErrorText = errText;
return false;
}
string regExString = String.Format(@"FA{0}-Z\d{{3}}", letter);
Regex shortRegEx = new Regex(regExString);
Regex longRegEx = new Regex(regExString + @"-\d+$");
bool isMatch = ((shortRegEx.IsMatch(str) && IsValidShortLength(str)) || (longRegEx.IsMatch(str) && IsValidLongLength(str)));
if (!isMatch)
{
this.ErrorText = errText;
}
return isMatch;
}
private static bool IsValidShortLength(string str)
{
return str.Length == 8;
}
private static bool IsValidLongLength(string str)
{
return (str.Length >= 10 && str.Length <= 12);
}