2

I am trying to validate input and handle exceptions in this program. Validating the following: strings in txtNAME should not be left blank, telephone number in txtTELEPHONE should be at least 10 digits, and txtEMAIL should be in email format with "@" and "." How do I validate these inputs and also handle exceptions in case the wrong input is entered?

public partial class Form1 : Form
{
    static int maxCount = 10;

    int[] employeeID = new int[maxCount];
    string[] employeeName = new string[maxCount];
    string[] jobTitle = new string[maxCount];
    string[] address = new string[maxCount];
    int[] telephoneNumber = new int[maxCount];
    string[] email = new string[maxCount];

    int addCount = 0;

    string fn = "employees.xml";

    int currentRec;

    private void btnADD_Click(object sender, EventArgs e)
    {
        employeeID[addCount] = Convert.ToInt32(txtEI.Text);
        employeeName[addCount] = txtNAME.Text;
        jobTitle[addCount] = txtJOB.Text;
        address[addCount] = txtADDRESS.Text;
        telephoneNumber[addCount] = Convert.ToInt32(txtTELEPHONE.Text);
        email[addCount] = txtEMAIL.Text;
        addCount++;
    }

    private void btnSAVE_Click(object sender, EventArgs e)
    {
      XmlTextWriter w = new XmlTextWriter(fn, Encoding.UTF8);
      w.Formatting = Formatting.Indented;
      w.WriteStartDocument();
      w.WriteStartElement("employees");
      for (int i = 0; i < addCount; i++)
      {
          w.WriteStartElement("employees");

          w.WriteElementString("employeeID", employeeID[i].ToString());
          w.WriteElementString("employeeName", employeeName[i]);
          w.WriteElementString("jobTitle", jobTitle[i]);
          w.WriteElementString("address", address[i]);
          w.WriteElementString("telephoneNumber", telephoneNumber[i].ToString());
          w.WriteElementString("email", email[i]);
          w.WriteEndElement();
      } w.WriteEndElement();
      w.WriteEndDocument();
      w.Close();
      Application.Exit();

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        if (File.Exists(fn))
        {
            XmlTextReader r = new XmlTextReader(fn);
            r.WhitespaceHandling = WhitespaceHandling.None;
            while (r.Name != "employees")
                r.Read();
            while (r.Name == "employees")
            {
                r.ReadStartElement("employees");
                employeeID[addCount] = Convert.ToInt32(r.ReadElementString("employeeID"));
                employeeName[addCount] = r.ReadElementString("employeeName");
                jobTitle[addCount] = r.ReadElementString("jobTitle");
                address[addCount] = r.ReadElementString("address");
                telephoneNumber[addCount] = Convert.ToInt32(r.ReadElementString("telephoneNumber"));
                email[addCount] = r.ReadElementString("email");
                r.ReadEndElement();
                addCount++;

            } r.Close();
            DisplayRec();
        }
    }

    private void DisplayRec()
    {
        txtEI.Text = employeeID[currentRec].ToString();
        txtNAME.Text = employeeName[currentRec];
        txtJOB.Text = jobTitle[currentRec];
        txtADDRESS.Text = address[currentRec];
        txtTELEPHONE.Text = telephoneNumber[currentRec].ToString();
        txtEMAIL.Text = email[currentRec];
        lblRECORD.Text = (currentRec + 1).ToString() + "/" + addCount.ToString();

    }

    private void btnBACK_Click(object sender, EventArgs e)
    {
        if (currentRec > 0)
            currentRec--;
        DisplayRec();
    }

    private void btnNEXT_Click(object sender, EventArgs e)
    {
        if (currentRec < addCount - 1)
            currentRec++;
        DisplayRec();
    }

    private void btnCLEAR_Click(object sender, EventArgs e)
    {
        txtEI.Clear();
        txtNAME.Clear();
        txtJOB.Clear();
        txtADDRESS.Clear();
        txtTELEPHONE.Clear();
        txtEMAIL.Clear();

    }
}
abatishchev
  • 98,240
  • 88
  • 296
  • 433
user3046541
  • 25
  • 1
  • 3
  • 1
    You have included quite a lot of unnecessary code. People will be more willing to help if you distill this down to the code that is applicable to your question. – Zach Spencer Feb 25 '14 at 03:51
  • As much as you might think, a telephone number is not a number - it's a sequence of numeric characters. In particular, depending on where you are and whether you include the country code a telephone number stored as a number might overflow a 32-bit integer. It's best to handle it as a string. – tvanfosson Feb 25 '14 at 04:04

6 Answers6

3

1. txtNAME should not be left blank,

to identify wether Name is null,Empty or WhiteSpace you can use String.IsNullOrWhiteSpace() method.

From MSDN : String.IsNullOrWhiteSpace()

Indicates whether a specified string is null, empty, or consists only of white-space characters.

Try This:

if(!String.IsNullOrWhiteSpace(txtNAME.Text))
{    
  //continue    
}
else
{
 MessageBox.Show("Error");    
}

2. txtTELEPHONE should be at least 10 digits,

You can use Length property of String to identify wether Telephone number is having 10 digits or not.

Try This:

if(txtTELEPHONE.Text.Length>=10)
{    
  //continue    
}
else
{    
MessageBox.Show("Error");    
}

3. txtEMAIL should be in email format with "@" and "."

For validating EmailID i would suggest you to use RegEx instead of only checking for @ and . characters.

Try This: Regular Expression

  Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
  Match match = regex.Match(txtEMAIL.Text);
  if (match.Success)
  {    
    //continue    
  }
  else
  {    
    MessageBox.Show("Error");    
  }

Try This: if you want to check for only @ and . characters

if(txtEMAIL.Text.Contains("@") && txtEMAIL.Text.Contains(".") )
{    
  //continue    
}
else
{    
MessageBox.Show("Error");    
}
Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67
2

in Save_click() method,call the method ValidateEntries() as follows

private void btnSAVE_Click(object sender, EventArgs e)
{
  if(validateEntries())
 {
  XmlTextWriter w = new XmlTextWriter(fn, Encoding.UTF8);
  w.Formatting = Formatting.Indented;
  w.WriteStartDocument();
  w.WriteStartElement("employees");
  for (int i = 0; i < addCount; i++)
  {
      w.WriteStartElement("employees");

      w.WriteElementString("employeeID", employeeID[i].ToString());
      w.WriteElementString("employeeName", employeeName[i]);
      w.WriteElementString("jobTitle", jobTitle[i]);
      w.WriteElementString("address", address[i]);
      w.WriteElementString("telephoneNumber", telephoneNumber[i].ToString());
      w.WriteElementString("email", email[i]);
      w.WriteEndElement();
  } w.WriteEndElement();
  w.WriteEndDocument();
  w.Close();
  Application.Exit();
}
}

   public bool VailidateEntries()
    {
      if (txtNAME.Text.Trim() == string.Empty)
        {
            MessageBox.Show("Name should not be empty");
            txtNAME.Focus();
            return false;
        }

      if (!(txtMailId.Text.Trim() == string.Empty))
      {
        if (!IsEmail(txtMailId.Text))
        {
            MessageBox.Show("Please enter valid Email Id's" );
            txtMailId.Focus();
            return false;
        }
     }

        if (!(txtPhone.Text.Trim() == string.Empty))
            {

                if (!IsPhone(txtPhone.Text))
                { 
                    MessageBox.Show("Invalid Phone Number");
                    txtPhone.Focus();
                    return false;
                }

            }
    }
    private bool IsEmail(string strEmail)
        {
            Regex validateEmail = new Regex(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                                       @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                                       @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
            return validateEmail.IsMatch(strEmail);
        }


        private bool IsPhone(String strPhone)
        {
            Regex validatePhone = new Regex("^([0-9]{3}|[0-9]{3})([0-9]{3}|[0-9]{3})[0-9]{4}$");
            return validatePhone.IsMatch(strPhone);
        }
sindhu jampani
  • 504
  • 3
  • 10
  • 30
1

I would consider using DataAnnotations and specifying as much of the requirements via attributes, with the remainder supplied by implementing IValidatableObject. Add the values into a collection of Employee objects and use the Validator.ValidateObject method to run validation on them. Then you can check whether you have any validation errors returned from that and do the appropriate thing.

This might also help with your XML serialization as you can also annotate it with XML attributes to help with that as needed - perhaps even creating the contain class Employees and setting it up so that you can use an XmlSerializer to automatically create the XML for you.

public class Employee : IValidatableObject
{
   public int Id { get; set; }

   [Required]
   [StringLength(50)]
   public string Name { get; set; }

   [Required]
   public string JobTitle { get; set; }

   [Required]
   public string Address { get; set; }

   [Required]
   [Phone]
   public string TelephoneNumber { get; set; }

   [Required]
   [EmailAddress]
   public string Email { get; set;

   public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
   {
       if (Id == 0)
       {
           yield return new ValidationResult("Employee Id must be greater than zero.", new [] { "Id" } );
       }
   }
}
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
0

For your third validation, you can use C# Regex.Match and learn the Regex expression via The 30 Minute Regex Tutorial?

V-SHY
  • 3,925
  • 4
  • 31
  • 47
0

Using Regular Expression will be better option as it will give you flexibility in modifying criteria. Helpful links from stackoverflow.

Regex Email validation C# Regex to validate phone number

Community
  • 1
  • 1
Avi
  • 1
  • 2
  • You should paste in the relevant code from those answers, and then cite the answers (as you have already done). – Tyler Feb 25 '14 at 04:23
0

What you're looking for is an ErrorProvider. You can use those, to verify your Windows-Forms quiet easily. I assume you're using the Design-Mode quiet often, so this would be the nicest solution for you, but not for your code quality. Search for the ErrorProvider in your Toolbar and add it to your form. You will then have the _ErrorProvider available as object in your form. Then you only have to bind Validation on your control for example:

txtTELEPHONE.Validating += ValidateName;

And the function:

private void ValidateName(object sender, CancelEventArgs e)
{
    // early initialization of errorMsg to fill it if necessary
    string errorMsg = null;

    // check your textbox
    if (String.IsNullOrEmpty(txtNAME.Text))
    {
        errorMsg = "No name provided!";
    }
    // this is the interesting part
    _ErrorProvider.SetError(lblTELEPHONE, errorMsg);
    e.Cancel = errorMsg != null;
}

The "_ErrorProvider.SetError" ties your error message using an icon to the label of the textfield. If the user hovers over that icon he or she can see the error message.

Any questions? Feel free to ask me :)

bastianwegge
  • 2,435
  • 1
  • 24
  • 30