9 Replies - 21831 Views - Last Post: 19 August 2011 - 04:36 AM Rate Topic: -----

#1 MjM8082  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 22
  • Joined: 17-August 11

How to validate blank text boxes in C#

Posted 17 August 2011 - 07:32 PM

I want my validator to be able to detect if a user left a text box blank. If so I want a message to come up in the feedback and say "error: blank field". I have been messing with the code, just not sure why I can't get this to work.

Here is my validator page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace ContactMgr
{
    public class Validator
    {

        public static bool Blank(string temp)
        {
            bool result = false;
            if (temp.Contains(""))
            {
                result = true;
            }
            return result;
        }
    }
}




That's my validation for the blank text box, here is my form.cs page...


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace ContactMgr
{
    public partial class Form1 : Form
    {
        //private class Person
        //{
        // private   string Prefix;
        // private string FName;
        //private string MName;
        //private string LName;
        //private string Street;
        // private string Street2;
        //private string City;
        // private string State;
        // private string Zip;

        // private string Email;

        //public string Feedback = "";






        // public Person()
        // {
        //    Prefix = "Mr.";


        //  }


        //  };

        public Form1()
        {
            InitializeComponent();
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {


            Person temp;

            temp = new Person();


            temp.FName = txtFName.Text;
            temp.MName = txtMName.Text;
            temp.LName = txtLName.Text;
            temp.Street = txtStreet.Text;
            temp.Street2 = txtStreet2.Text;
            temp.City = txtCity.Text;

            temp.State = txtState.Text;
            temp.Zip = txtZip.Text;

            temp.Email = txtEmail.Text;

            if (temp.LName == "McCarthy")
            {

                DisplayInfo(temp);
            }

            // if (temp.FName.Length > 0 && temp.LName.Length > 0)
            if (!String.IsNullOrWhiteSpace(temp.FName) && !String.IsNullOrWhiteSpace(temp.LName))
            {
                DisplayInfo(temp);
            }
            else if (!String.IsNullOrWhiteSpace(temp.Feedback))
            {
                lblFeedback.Text = temp.Feedback;
            }
            {
                {
                    dtpStartTime.CustomFormat = "MM/dd/yyyy HH:mm:ss tt";
                    dtpStartTime.MaxDate = DateTime.Now.AddYears(1);

                    MessageBox.Show(dtpStartTime.Value.ToString());
                }
                if (txtFName.Text == "")
                {
                    MessageBox.Show(
                        "First Name is a required field.", "Entry Error");
                    txtFName.Focus();
                }
                if (txtMName.Text == "")
                {
                    MessageBox.Show(
                        "Middle Name is a required field.", "Entry Error");
                    txtMName.Focus();
                }
                if (txtLName.Text == "")
                {
                    MessageBox.Show(
                        "Last Name is a required field.", "Entry Error");
                    txtLName.Focus();
                }

            }

        }


       private void DisplayInfo(Person temp)
       {
            lblFeedback.Text = temp.Prefix + " " + temp.FName + " " + temp.MName + " " + temp.LName + " " + temp.Street + " " + temp.Street2 + " " + temp.City + " " + temp.State + " " + temp.Zip + " " + temp.Email;

        }

        private void DisplayInfo()
        {
            lblFeedback.Text = "unknown person, need more data";

        }


    }
}






And my person.cs page


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ContactMgr
{
    public class Person
    {
        private string fName;
        private string mName;
        private string lName;
        public string City;
        public string Email;
        public string Prefix;
        public string State;
        public string Street;
        public string Street2;
        public string Zip;
       


        public string feedback = "";



        public Person()
        {
        }

        public string FName
        {
            get
            {
                return fName;
            }
            set
            {
                if (Validator.Blank(value))
                {
                    feedback += "ERROR: Blank Field";
                }
                else
                {
                    fName = value;
                }
            }
        }

     
        public string MName
        {
            get
            {
                return mName;
            }
            set
            {
                if (Validator.ContainsBadWords(value))
                {
                    feedback += "ERROR: Bad Word in Middle Name\n";

                }
                else
                {
                    mName = value;
                }
            }
        }

        public string LName
        {
            get
            {
                return lName;
            }
            set
            {
                if (Validator.ContainsBadWords(value))
                {
                    feedback += "ERROR: Bad Word in Last Name\n";

                }
                else
                {
                    lName = value;
                }
            }
        }

        public string Feedback
        {
            get
            {
                return feedback;
            }
            set
            {
                if (Validator.ContainsBadWords(value))
                {
                    feedback += "ERROR: Bad Word in Feedback\n";
                }
                else
                    feedback = value;
            }
        }
    }



}


Is This A Good Question/Topic? 0
  • +

Replies To: How to validate blank text boxes in C#

#2 modi123_1  Icon User is online

  • Suitor #2
  • member icon



Reputation: 9393
  • View blog
  • Posts: 35,273
  • Joined: 12-June 08

Re: How to validate blank text boxes in C#

Posted 17 August 2011 - 08:27 PM

You are asking if a string contains nothing... that doesn't make sense. Why not check if the string equals empty? Contains is not equal.
Was This Post Helpful? 1
  • +
  • -

#3 karabasf  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 202
  • View blog
  • Posts: 417
  • Joined: 29-August 10

Re: How to validate blank text boxes in C#

Posted 18 August 2011 - 12:16 AM

As a follow up to modi's argument, it makes no sense to call a contains class. Suppose the user enters this in the textfield:

" DATA", as you see the string contains " ", returning a boolean true, giving me the error that my textfield is empty (which is not).

In order to have a proper validation, you could use the equals method (temp.Equals(" ") and/or temp.Equals(null). A method which simplifies this typing is the IsNullOrEmpty method of the string class:

http://msdn.microsof...ullorempty.aspx

This method will return a boolean true if the string is empty or null; false if otherwise.

If you would require that the user may not leave the textfield empy, you could use the String.IsNullOrWhiteSpace method: http://msdn.microsof...whitespace.aspx

This method returns a boolean true if either the string is empty, null or contains only whitespaces; false if otherwise.

Regarding which string method you use, as both of these methods return a boolean, you can simplify your validator significantly.

Hope this helps you out ^^

This post has been edited by karabasf: 18 August 2011 - 12:22 AM

Was This Post Helpful? 1
  • +
  • -

#4 RudiVisser  Icon User is offline

  • .. does not guess solutions
  • member icon

Reputation: 1004
  • View blog
  • Posts: 3,562
  • Joined: 05-June 09

Re: How to validate blank text boxes in C#

Posted 18 August 2011 - 12:40 AM

Personally, I have always defined a minimum length per text box, and validated that way.

There's a minor problem with this, in that the user can enter ' ' for example, and it would validate, so you simply Trim the value and report based on that. Using a method for empty checking won't really help you as the string may not be empty, but still not have any printable characters.

A simple check such as this:
if (myTextBox.Text.Trim().Length < 3) { /* Nothing entered! */ }
would probably be suffice..

You can of course take it further than Trim, but if the user really wants to break your application that much then let them be.

This post has been edited by RudiVisser: 18 August 2011 - 12:41 AM

Was This Post Helpful? 0
  • +
  • -

#5 fixo  Icon User is offline

  • D.I.C Regular

Reputation: 85
  • View blog
  • Posts: 335
  • Joined: 10-May 09

Re: How to validate blank text boxes in C#

Posted 18 August 2011 - 04:12 AM

Why don't you use events Just a thoughts
E.g. on form load event you can add these lines:
     this.textBox1.Validating += new CancelEventHandler(textBox1_Validating);
            this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);

//then you would be write something like:
    void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {

            this.textBox1.Validating -= new CancelEventHandler(textBox1_Validating);
        }

        void textBox1_Validating(object sender, CancelEventArgs e)
        {
            TextBox tbox = (TextBox)sender as TextBox;

            if (tbox.Text == "")
            {

                MessageBox.Show("Enter value to " + tbox.Name);
         
                return;
            }

        }

Was This Post Helpful? 1
  • +
  • -

#6 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5583
  • View blog
  • Posts: 11,941
  • Joined: 02-June 10

Re: How to validate blank text boxes in C#

Posted 18 August 2011 - 07:20 AM

I don't think you are taking the time to read and learn the methods you are trying to use. As a result you get behavior you can't explain and don't understand. This was the case with your last thread for a different situation with your Validator and it is the case here.

Take this block of code for example:
if (temp.Contains(""))
            {
                result = true;
            }



The part you don't seem to have a handle on is the string.Contains() method. You are using it as if it really says "string.OnlyContains" which would be the same as equals.

But that's not what .Contains means. It means "in addition to any other characters, does it somewhere .Contain('x') For exaple
string yogi = "bear";
if (yogi.Contains('e')
{
   // Do something
   // This will happen because "bear" does contain an 'e', 
   // but it does not ONLY contain an 'e'
}


I hate to sound like I am beating on you about debugging, but had you put a breakpoint on line 13 of this method

11 public static bool Blank(string temp)
12 {
13 bool result = false;
14 if (temp.Contains(""))
15 {
16 result = true;
17 }
18 return result;
19 }

Then walked through the execution with the F10 key, you would have observed that temp.Contains was always false and thus always skipped over the exectution of the result=true block.

From there curiosity and common sense should have kicked in, something along these lines.
... Huh? My if check always fails. Why would that be?
... Maybe I should read up on the .Contains since that is the heart of my if
... Oh... It works differently than I thought

But it all starts with actually watching your code execute line by line, and observing if your conditionals do what you theorize they will do, and observing the variable values. If you don't do that, then you are just pissing in the wind: Guessing you know which way it will go.

We have to guide new coders to debugging a LOT. I keep thinking I should make a tutorial for it. Then I realize "Oh wait, there are several here" and "I don't think I could be any more complete than this one I keep pointing people to."
http://beyondrelatio...spx#heading0024
Was This Post Helpful? 3
  • +
  • -

#7 MjM8082  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 22
  • Joined: 17-August 11

Re: How to validate blank text boxes in C#

Posted 18 August 2011 - 10:00 PM

I want to validate if the user leaves the text box blank. I want my feedback label to say "Error: Blank Field".


Not sure how I would make my validator do this.

I'm thinking it needs to be something like this?

public static bool BlankField (string temp)
{
bool result = false;
if (txtWho.Text == "")
} 
else
{
result = true;


I think it should be something like that? Not entirely sure.

Here is my code pages.


Form.cs


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ApptMgr
{
    public partial class Form1 : Form
    {
        public string Who;
        public string Where;
        public string Comments;


       

        public Form1()
        {
            InitializeComponent();
        }

        
        private void button1_Click(object sender, EventArgs e)
            
        {
            

            Appointment temp;

            temp = new Appointment();

            temp.Who = txtWho.Text;
            temp.Where = txtWhere.Text;
            temp.Comments = txtComments.Text;


           

            if (txtWho.Text == "")
            {
                MessageBox.Show(
                    "Who is a required field.", "Entry Error");
                txtWho.Focus();
            }
            if (txtWhere.Text == "")
            {
                MessageBox.Show(
                    "Where is a required field.", "Entry Error");
                txtWhere.Focus();
            }

            if (txtWho.Text.Length >= 50)
            {
                MessageBox.Show("Invalid Input. Value must be less than 50 characters");
            }

            if (txtWhere.Text.Length >= 30)
            {
                MessageBox.Show("Invalid Input. Value must be less than 30 characters");
            }
           
           
         

            dtpStartTime.CustomFormat = "MM/dd/yyyy HH:mm:ss tt";
            dtpStartTime.MaxDate = DateTime.Now.AddYears(1);

            MessageBox.Show(dtpStartTime.Value.ToString());


            dtpEndTime.CustomFormat = "MM/dd/yyyy HH:mm:ss tt";
            dtpEndTime.MaxDate = DateTime.Now.AddYears(1);

            MessageBox.Show(dtpEndTime.Value.ToString());


            if (!String.IsNullOrWhiteSpace(temp.Who) && !String.IsNullOrWhiteSpace(temp.Where))
            {
                DisplayInfo(temp);
            }
            else if (!String.IsNullOrWhiteSpace(temp.Feedback))
            {
                lblFeedback.Text = temp.Feedback;
            }

           

        }

        private void dtpStartTime_ValueChanged(object sender, EventArgs e)
        {

        }

        private void DisplayInfo(Appointment temp)

        {
            lblFeedback.Text = txtWho.Text + " " + txtWhere.Text + " " + txtComments.Text;


        }

       
        
    }
}



and right now my validator page is empty
Was This Post Helpful? -1
  • +
  • -

#8 Momerath  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1012
  • View blog
  • Posts: 2,444
  • Joined: 04-October 09

Re: How to validate blank text boxes in C#

Posted 18 August 2011 - 10:09 PM

You'll get the exact same answers you got in your other thread of the exact same subject. http://www.dreaminco...-boxes-in-c%23/
Was This Post Helpful? 0
  • +
  • -

#9 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6078
  • View blog
  • Posts: 23,549
  • Joined: 23-August 08

Re: How to validate blank text boxes in C#

Posted 19 August 2011 - 03:12 AM

Merged duplicate topics. Do NOT open a new topic on the same subject as a topic you already have open.
Was This Post Helpful? 0
  • +
  • -

#10 Bloosdhed  Icon User is offline

  • New D.I.C Head

Reputation: 17
  • View blog
  • Posts: 22
  • Joined: 18-August 11

Re: How to validate blank text boxes in C#

Posted 19 August 2011 - 04:36 AM

Why not put the validation in the class?
Also if the user fails to enter more than 1 field correct it will result in multiple messagebox popups (annoying).

    class Appointment
    {
        public string Who { get; set; }
        public string Where { get; set; }
        public string When { get; set; }

        public Appointment()
        {
            Who = "";
            Where = "";
            When = "";
        }
        public Appointment(string who, string where, string when)
        {
            Who = who;
            Where = where;
            When = when;
        }

        public bool Validate()
        {
            var validationMessage = new StringBuilder();

            if (Who == "")
                validationMessage.Append("Who is not specified.\n\n");

            if (Where == "")
                validationMessage.Append("Where is not specified.\n\n");

            if (When == "")
                validationMessage.Append("When is not specified.\n\n");

            if (validationMessage.ToString() != "")
            {
                MessageBox.Show(validationMessage.ToString(), "Appointment Notification", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }

            return true;
        }

        public void Save()
        {
            //Save this
            MessageBox.Show("Appointment Saved", "Appointment Notification", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }



In your form or w/e you can just do this after you set the properties according to the textbox.Text:

if (appointment.Validate())
    appointment.Save();

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1