Assignment
In this exercise I will ask you to create two classes to hold data from user input. We will use the console to retrieve our data by asking the user to create the object.
1. Create a Console application;
2. Create a class named Client;
3. Add the following properties to your Client class : FirstName, LastName, Email, Address, PhoneNumber;
4. Create a parameter and a default constructor for the client class.
5. Create a class named Validator;
6. Create 3 methods in your validation with the following signatures: bool ValidateIfEmptyField(string Text), bool ValidateEmail(string Email), bool ValidatePhoneNumber(string PhoneNumber).
7. With a little bit of research, you can even set the Validator class to static.
In the program.vb/program.cs class, you need to ask the user for the information to create a client, then validate the entered information and finally create the client object by using the information provided.
The last thing you will want to do is to display the client in the console (you can implement the ToString() method if you want!). Remember what String concatenation was, it might help you.
Here is an example of the program output :
Please enter the client first name: Alexandre Please enter the client last name: Sauve Please enter his/her email: test@test.com Please enter his/her address: 56000 test rd. finally enter the phone number: 888888888 Client information: FirstName: Alexandre LastName: Sauve Email: test@test.com Address: 56000 test rd. PhoneNumber: 8888888888
Note: for the validation, you can do basic validation, like the phone number size (10), you don’t have to complicate things. But if you really want a challenge, you can try the regular expressions! Good luck!
Solution
For the solution to this exercise, let’s start by creating the tools we will need, that is, the classes and the Console Application.
There will be two classes, the validator and the Client. Remember to name classes with a singular name because it will be the representation of one object of this type.
You should now have a ready console application as well as two classes like the following.
Visual Basic
C#
Client
Visual Basic
Option Strict On Option Explicit On Public Class Client End Class
C#
namespace Exercise5 { public class Client { } }
Validator
Visual Basic
Option Strict On Option Explicit On Public Module Validator End Module
C#
namespace Exercise5 { public static class Validator { } }
As you can probably notice, my Validator class is static (we use a Module in Visual Basic) which makes sure that there is only one instance of this class (module) in the software. Another advantage of this approach will be that we can call this class without instanciating it, that is, by calling Validator.MyMethod() directly! A static class (module) might apply if we want to use the Validator in multiple places but be careful not to use too many static classes (modules)! Also, both classes are public (because we want to be able to use them from our Program class).
If we review our steps, we have step 1, 2 and 5 completed! It’s time to add some Properties to the Client class. We need to add FirstName, LastName, Email, Address and PhoneNumber.
Client Class
Visual Basic
Option Strict On Option Explicit On Public Class Client 'Properties Public Property FirstName As String Public Property LastName As String Public Property Email As String Public Property Address As String Public Property PhoneNumber As String 'Constructors Public Sub New(FirstName As String, LastName As String, Email As String, Address As String, PhoneNumber As String) Me.FirstName = FirstName Me.LastName = LastName Me.Email = Email Me.Address = Address Me.PhoneNumber = PhoneNumber End Sub Public Sub New() FirstName = "Alexandre" LastName = "Sauve" Email = "test@test.com" Address = "450 testing St." PhoneNumber = "8888888888" End Sub 'ToString method override (for user friendly client output) Public Overrides Function ToString() As String Return "First Name: " & FirstName & vbCrLf & "Last Name: " & LastName & vbCrLf & "Email: " & Email & vbCrLf & "Address: " & Address & vbCrLf & "Phone Number: " & PhoneNumber & vbCrLf End Function End Class
C#
namespace Exercise5 { public class Client { public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public string Address { get; set; } public string PhoneNumber { get; set; } public Client(string FirstName, string LastName, string Email, string Address, string PhoneNumber) { this.FirstName = FirstName; this.LastName = LastName; this.Email = Email; this.Address = Address; this.PhoneNumber = PhoneNumber; } public Client() { FirstName = "Alexandre"; LastName = "Sauve"; Email = "Test@hotmail.com"; Address = "450 Test St."; PhoneNumber = "2833939292"; } public override string ToString() { return "FirstName: " + FirstName + "\n" + "LastName: " + LastName + "\n" + "Email: " + Email + "\n" + "Address: " + Address + "\n" + "PhoneNumber: " + PhoneNumber; } } }
I added the two requested constructors as well, one parameters and one default. Why is there the this. keyword before my properties in the Client constructor? That’s because I am using the same names for my local variables and my parameters, the compiler isn’t sure which one is which so I have to be a bit more specific and tell it that I want the property set to the value of the local variable. Finally, I decided to add all string parameters since the phone number might have different implementation and because I don’t want to do a lot of validation since we’re talking about classes and not validation!
I decided to add the ToString() method for convenience when we will want to display the Client class properties in the console.
Our client class is now complete and ready to be used in our program.
Validator Class
The validator class is meant to offer a few methods to validate components of the user input. It would be a better idea to separate the validation if we had more forms to validate, but we are still going to use this class in case we want to add more in the future. The input we are going to validate are : PhoneNumber (simply the length) and the email using a regular expression.
Visual Basic
Option Strict On Option Explicit On Imports System.Text.RegularExpressions Public Module Validator Public Function FieldIsEmpty(ByVal Value As String) As Boolean If String.IsNullOrEmpty(Value) Then Return True End If Return False End Function Public Function PhoneNumberIsValid(ByVal PhoneNumber As String) As Boolean If PhoneNumber.Length = 10 Then Return True End If Return False End Function Public Function EmailIsValid(ByVal Email As String) As Boolean If Regex.IsMatch(Email, "^[^@]+@[^@]+\.[^@]+$") Then Return True End If Return False End Function End Module
C#
using System.Text.RegularExpressions; namespace Exercise5 { public static class Validator { public static bool FieldIsEmpty(string Value) { if (String.IsNullOrEmpty(Value)) return true; return false; } public static bool PhoneNumberIsValid(string PhoneNumber) { if (PhoneNumber.Length == 10) return true; return false; } public static bool EmailIsValid(string Email) { if (Regex.IsMatch(Email, "^[^@]+@[^@]+\\.[^@]+$")) return true; return false; } } }
The first method simply verifies if the provided value is null or empty and return true if that`s not the case and false if that is the case. Why is the method inverted like this? That’s because of the name I chose, FieldIsEmpty -> yes (true), if it’s not empty, it’s going to return false. If you prefer to have the IsValid – True and IsInvalid – False pattern, you can rename the method FieldIsNotEmpty. You will then have to be careful in the main processing because every call to this method will be inverted for you.
You should notice that all the methods are static since this is a static class (that doesn’t mather in Visual Basic since it’s a Module, this is done implicitly), all methods must have the static modifier. The second method, PhoneNumberIsValid, verifies that the phone number is a 10 digits phone number, nothing out of the ordinary and not the best validation but it will do for our example.
The third method uses a Regular expression, I will talk a bit more about regular expressions in another tutorial but for now you must know that the string sent as a parameter to the IsMatch method and that looks like hieroglyphs is what the email will be tested against. If it passes, the method returns True and if it fails, the method returns False. You may notice that I added a special using (imports in Visual Basic) to access the Regex class because it is contained in another namespace (or container if you prefer).
We got both our classes done and the steps 3, 4, 6, 7 are complete! We’re now ready for user input.
User Input
Visual Basic
Option Strict On Option Explicit On Module Program Sub Main() 'Validate all input fields to retrieve information from the user about the client Dim FirstName As String = String.Empty While Validator.FieldIsEmpty(FirstName) Console.WriteLine("Please enter the client first name: ") FirstName = Console.ReadLine() End While Dim LastName As String = String.Empty While Validator.FieldIsEmpty(LastName) Console.WriteLine("Please enter the client last name: ") LastName = Console.ReadLine() End While Dim Email As String = String.Empty While Validator.FieldIsEmpty(Email) Or Not Validator.EmailIsValid(Email) Console.WriteLine("Please enter the client email: ") Email = Console.ReadLine() End While Dim Address As String = String.Empty While Validator.FieldIsEmpty(Address) Console.WriteLine("Please enter the client address: ") Address = Console.ReadLine() End While Dim PhoneNumber As String = String.Empty While Validator.FieldIsEmpty(PhoneNumber) Or Not Validator.PhoneNumberIsValid(PhoneNumber) Console.WriteLine("Please enter the client phone number: ") PhoneNumber = Console.ReadLine() End While 'Create a new client object to store the client values Dim NewClient As New Client(FirstName, LastName, Email, Address, PhoneNumber) 'Display the client in the console with our implemented ToString method Console.Write(NewClient.ToString()) Console.ReadKey() End Sub End Module
C#
using System; namespace Exercise5 { class Program { static void Main(string[] args) { //Validate and store all client input values string FirstName = String.Empty; while(Validator.FieldIsEmpty(FirstName)) { Console.WriteLine("Please enter the client first name: "); FirstName = Console.ReadLine(); } string LastName = String.Empty; while (Validator.FieldIsEmpty(LastName)) { Console.WriteLine("Please enter the client last name: "); LastName = Console.ReadLine(); } string Email = String.Empty; while (Validator.FieldIsEmpty(Email) || !Validator.EmailIsValid(Email)) { Console.WriteLine("Please enter the client email: "); Email = Console.ReadLine(); } string Address = String.Empty; while (Validator.FieldIsEmpty(Address)) { Console.WriteLine("Please enter the client address: "); Address = Console.ReadLine(); } string PhoneNumber = String.Empty; while (Validator.FieldIsEmpty(PhoneNumber) || !Validator.PhoneNumberIsValid(PhoneNumber)) { Console.WriteLine("Please enter the client phone number: "); PhoneNumber = Console.ReadLine(); } //At this point we have all the required information, we can create our object! Client NewClient = new Client(FirstName, LastName, Email, Address, PhoneNumber); //Display the client with the ToString method Console.Write(NewClient.ToString()); Console.ReadKey(); } } }
Each validation phase is similar, we will accept user input until the result satisfies the stated conditions by using a while loop. You can use this strategy whenever you want to force the user to input a correct value in the console. Lastly, we create our client with all the gathered information and use the ToString() method from our newly created user to display its properties.
This exercise was a little more complicated than what we’ve done so far. I strongly suggest that you take more time to understand what is going on and give this code some testing on your own. Don’t be afraid to use breakpoints and look things up on the Internet.
Here is the final result
I you have any questions related to this exercise, feel free to post them in the comments!
YouTube
Visual Basic
C#
No Comments Yet!
You can be first to comment this post!