I doubt if we should use any exceptions here, routine (and a bit tedious) checking is enough.
Let's redesign Validation
method: we'll return either empty string (for no error) or corresponding error message:
using System.Linq;
...
private static string ValidationMessage(string s) {
if (null == s)
return "null string";
if (s.Length > 15)
return "Vous avez entré trop de caractères";
if (s.Length < 15)
return "Vous n'avez pas entré assez de caractères";
if (!s.All(c => c >= '0' && c <= '9')) // all characters in s are [0..9] digits
return "Valeur non numérique";
if (s[0] != '1' && s[0] != '2')
return "Genre inconnu";
int mois = int.Parse(s.Substring(3, 2));
if (mois < 1 || mois > 12)
return "Le mois entré est incorrect";
long clef = 97 - long.Parse(s.Substring(0, 13)) % 97;
long r2 = long.Parse(s.Substring(13, 2));
if (r2 != clef)
return "La clef est incorrecte";
return "";
}
Then we can use it:
private void btn_Click(object sender, EventArgs e) {
string errorMessage = ValidationMessage(TxtNumSS.Text);
if (string.IsNullOrEmpty(errorMessage)) {
//TODO: check: should we clear TxtNumSS here?
TxtNumSS.Clear();
MessageBox.Show("Clef valide! ");
}
else
MessageBox.Show("error", errorMessage, MessageBoxButtons.YesNo);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…