[英]have email and phone number in correct format using a object class
我正在尝试为我的联系人管理器应用程序创建一个联系人类,我需要电子邮件必须包含 1 个且仅包含 1 个 @ 符号,并确保电话号码的格式为 123-456-7890,但我不知道如何做这个。
任何指导将不胜感激
class Contact
{
class Contact
{
//private member variables
private String _firstName;
private String _lastName;
private Type _contactTypes;
private String _phoneNumber;
private String _emailAddress;
//Public constructor that takes five arguments
public Contact()
{
//Call the appropriate setter (e.g. FirstName) to set the member variable value
/* GetFirstName = firstName;
GetLastName = lastName;
ContactTypes = contactTypes;
GetPhoneNumber = phoneNumber;
GetEmailAddress = emailAddress;*/
}
/*********************************************************************
* Public accessors used to get and set private member variable values
*********************************************************************/
//Public ContactTypes accessor
public Type ContactTypes
{
get
{
//Return member variable value
return _contactTypes;
}
set
{
//Validate value and throw exception if necessary
if (value == null)
throw new Exception("ContactType must have a value");
else
//Otherwise set member variable value*/
_contactTypes = value;
}
}
enum ContactTypesEnum { Family, Friend, Professional }
//Public FirstName accessor: Pascal casing
public String GetFirstName
{
get
{
//Return member variable value
return _firstName;
}
set
{
//Validate value and throw exception if necessary
if (value == "")
throw new Exception("First name must have a value");
else
//Otherwise set member variable value
_firstName = value;
}
}
//Public LastName accessor: Pascal casing
public String GetLastName
{
get
{
//Return member variable value
return _lastName;
}
set
{
//Validate value and throw exception if necessary
if (value == "")
throw new Exception("Last name must have a value");
else
//Otherwise set member variable value
_lastName = value;
}
}
//Public PhoneNumber accessor
public String GetPhoneNumber
{
get
{
//Return member variable value
return _phoneNumber;
}
set
{
bool isValid = Regex.IsMatch(value, @"/d{3}-/d{3}-/d{4}");
//Validate value and throw exception if necessary
if (value == "")
throw new Exception("PhoneNumber must have a value");
else
//Otherwise set member variable value
_phoneNumber = value;
}
}
//Public Email accessor
public String GetEmailAddress
{
get
{
//Return member variable value
return _emailAddress;
}
set
{
//Validate value and throw exception if necessary
if (value == "")
throw new Exception("EmailAddress must have a value");
else
//Otherwise set member variable value
_emailAddress = value;
}
}
}
}
我同意@Enigmativity 的评论 - 在访问器集函数中抛出异常不是一个好主意。 话虽如此,您已经完成了GetPhoneNumber
isValid
正则表达式测试。
set
{
bool isValid = Regex.IsMatch(value, @"/d{3}-/d{3}-/d{4}");
if (isValid) // Set member variable value
_phoneNumber = value;
}
您可以对电子邮件进行类似的正则表达式测试,也可以使用System.Net.Mail.MailAddress
类。 请参阅此 SO 响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.