Reputation: 37
I'm trying to make a contact class represent individual contacts that would appear in my contact manager application. I need to check that the phone number is in the format 123-456-7890 but I am not sure as how to do this?
Code:
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(String firstName, String lastName, Type contactTypes, String phoneNumber, String emailAddress)
{
//Call the appropriate setter (e.g. FirstName) to set the member variable value
FirstName = firstName;
LastName = lastName;
ContactTypes = contactTypes;
PhoneNumber = phoneNumber;
EmailAddress = 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 == "")
throw new Exception("ContactType must have a value");
else
//Otherwise set member variable value
_lastName = value;
}
}
enum ContactTypes { 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
{
//Validate value and throw exception if necessary
if (value == "")
throw new Exception("PhoneNumber must have a value");
else
//Otherwise set member variable value
_lastName = 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;
}
}
Upvotes: 2
Views: 478
Reputation: 7668
You can use the following Regular Expression
bool isValid = Regex.IsMatch(value, @"/d{3}-/d{3}-/d{4}");
Upvotes: 3
Reputation: 3480
You can use the following article which contains a code example how to use it:
http://www.authorcode.com/how-to-use-regular-expression-for-validating-phone-numbers-in-net/
Upvotes: 0