C#で電子メール検証プログラムを作成しましたが、文字列外のデータをチェックするにはどうすればよいですか?
これが私のC#コードです:
private bool CheckEmail()
{
string email1 = email.Text;
//calculating the length of the email
int EmailLen = email1.Length;
int num = 0;
//the first character of the email must not be the "@"
if (email1.Substring(0, 1) != "@")
{
//checking the email entered after the first character as it is not a "@" so i will start from 1.
for (int i = 1; i < EmailLen; i++)
{
//prevents there from being two "@"next to each other
if (email1[i] == '@' && (i + 1) < email1.Length && email1[i + 1] != '@')
{
//if there is an "@" in the email then num will increase by one
num = num + 1;
//now the stored value of i is the position where the "@" is placed. j will be i+2 as there should be at least one character after the "@"
int j = i + 2;
if (j < EmailLen)
{
for (int k = j; k < EmailLen; k++)
{
//when it finds a "." In the email, the character after the "." Should not be empty or have a space, e.g. it should be something like ".com"
if (email1[k] == '.' && k + 1 < email1.Length && email1[k + 1] != ' ')
{
num = num + 1;
}
}
}
else
{
break;
}
}
}
}
else
{
num = 0;
}
//if the num is 2, then the email is valid, otherwise it is invalid. If the email had more than one "@" for example, the num will be greater than 2.
if (num == 2)
{
return true;
}
else
{
return false;
}
}
「aa@」と入力しようとすると、「インデックスと長さは文字列内の場所を参照する必要があります。」というエラーが表示されます。</ p>
aa@aと入力するとき。、次のエラーが発生します:「インデックスと長さは文字列内の場所を参照する必要があります。」</ p>