Textbox validation in a Windows Form - c#

I want to put a validation that the user always enters a value in the textbox before submiting the form. But the check that I have put allows user to enter white spaces and continue submitting the form.
So, how to put the check so that the user in not able to submit the form if there are only white spaces in the textbox.

You can make your own custom validation function. This may be very naive, but somehow it will work.
private bool WithErrors()
{
if(textBox1.Text.Trim() == String.Empty)
return true; // Returns true if no input or only space is found
if(textBox2.Text.Trim() == String.Empty)
return true;
// Other textBoxes.
return false;
}
private void buttonSubmit_Click(object sender, EventArgs e)
{
if(WithErrors())
{
// Notify user for error.
}
else
{
// Do whatever here... Submit
}
}

in NET4.0 there is a nice function
if(string.IsNullOrWhiteSpace(textBox1.Text))
{
//raise your validation exception
}
else {
//go to submit
}

It can be easily be done using error provider here is the code.Error Provider you can find in your toolbox.
private void btnsubmit_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtname.Text))
{
txtname.Focus();
errorProvider1.SetError(txtname, "Please Enter User Name");
}
if (string.IsNullOrEmpty(txtroll.Text)) {
txtroll.Focus();
errorProvider1.SetError(txtroll, "Please Enter Student Roll NO");
}
}
Here is output image

Related

Validate two textboxes (C #)

I have two textboxes, which prompts the user to enter an integer in each of them. I already have the code all done (code to validate if the texboxes are not empty, if only integers are entered and if the number inserted in the 2nd texbox is greater than the number entered in the 1st texbox.
I leave here a simple example of my code (I already have all the code done):
private async void generate_Click(object sender, RoutedEventArgs e)
{
if (String.IsNullOrWhiteSpace(min.Text) || String.IsNullOrWhiteSpace(max.Text))
{
// I already have the code done ...
// error message
}
else
{
// I already have the code done ...
// Here it does the operation with the two numbers entered
}
}
private async void min_TextChanged(object sender, TextChangedEventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(min.Text, "[^0-9]"))
{
// I already have the code done ...
// error message
}
}
private async void max_TextChanged(object sender, TextChangedEventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(max.Text, "[^0-9]"))
{
// I already have the code done ...
// error message
}
}
I only have one question: Where do I put the code (I already have this code done) to verify that the number entered in the 2nd textbox is greater than the number entered in the 1st texbox? This is my question.
Update: I just want to know where I put the code:
if (maxValue < minValue)
{
// I already have the code done ...
// error message
}
Encapsulate all of this validation logic in a function the returns a bool
private bool IsValid ()
{
if (String.IsNullOrWhiteSpace(min.Text) || String.IsNullOrWhiteSpace(max.Text))
{
// return false any where the input is not valid
}
}
then use an if statment inside Your Button click Event Handler
if (IsValid())
{
//Code To Check If Max is Bigger Than min
}
this Way You Can Easily Call The IsVaild Function To Check For Empty String
You Can Also Encapsulate The Logic To Validate The Bigger Number in Another function if u gonna use it alot
Hope I Fully Understood You
If your confusion is only where to put the verification code of the number entered in the 2nd textbox is greater than the number entered in the 1st textbox, you can simply check this after the button click. Here's the sample:
private async void generate_Click(object sender, RoutedEventArgs e)
{
if (String.IsNullOrWhiteSpace(min.Text) || String.IsNullOrWhiteSpace(max.Text))
{
await new MessageDialog("Text boxes cannot be empty").ShowAsync();
return;
}
if (Convert.ToInt32(max.Text) < Convert.ToInt32(min.Text))
{
await new MessageDialog("1st one is bigger").ShowAsync();
//you may do as you want, showing a message box is just a sample
}
else
{
await new MessageDialog("2nd one is bigger").ShowAsync();
//you may do as you want, showing a message box is just a sample
}
}
And for your clarification onTextChanged events may be like this:
private async void min_TextChanged(object sender, TextChangedEventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(min.Text, "[^0-9]") )
{
await new MessageDialog("Enter numbers only.").ShowAsync();
//you may do as you want, showing a message box is just a sample
}
}
private async void max_TextChanged(object sender, TextChangedEventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(max.Text, "[^0-9]"))
{
await new MessageDialog("Enter numbers only.").ShowAsync();
//you may do as you want, showing a message box is just a sample
}
}
So here the summary is, if the textboxes are empty it will show a warning and return. And after the user finishes the input number and presses the button it will check which number is bigger. And a warning will also showed if users give input rather than numbers. Hope this may help you.

Errorprovider c# winforms

Im working with errorprovider in a c# winforms application.
Now I want to have a "double" validation. Once on the textfields directly, so the user sees that he has made some errors, and once on the button itself. So when there are still errors, the "save" button will keep greyed out or "disabled".
Because I don't want to block my user when he is making an error, and I want him to be able to make the changes whenever he wants im using the event "leave" or on focus lost. This because otherwise I noticed you cannot go to another field, until you changed your error.
So, now the code:
private void txtFirstname_Leave(object sender, EventArgs e)
{
if (!InputChecks.IsFilledIn(txtFirstname.Text))
{
errorProvider1.SetError(txtFirstname, "Firstname needs to be filled in!");
isValidated = false;
}
else
{
errorProvider1.SetError(txtFirstname, "");
isValidated = true;
}
}
So far, so good. The error provider works correctly and my user can edit whenever he wants.
public void setSaveButton()
{
if (isValidated == true)
{
btnSave.Enabled = true;
}
else
{
btnSave.Enabled = false;
}
}
bool isValidated;
private void btnSave_Click(object sender, EventArgs e)
{
if (isValidated == true)
{
employeePresenter.addEmployee(txtFirstname.Text, txtLastname.Text, txtUsername.Text, txtPassword.Text);
}
}
This was still okey in my head. BUT, as I give the ability to the user to change the issues whenever they want, this doesn't work. I tried to put the method "setSaveButton()" under "isvalidated" but this is not working either. Because of the focus lost.
Anyone has a better idea for this? I have been looking on google and the only things i found was a single validation with the errorprovider, or the event validating. But these events don't allow users to edit their errors whenever they want. It blocks them into one particular text field.
You don't need to make the save button disabled. It's enough to check ValidateChildren method of your form and if it returned false, it means there is some validation error. To use this approach you should remember to set e.Cancel = true in Validating event of the control when you set an error for control.
Also to let the user to move between controls even if there is an error, set AutoValidate property of your Form to EnableAllowFocusChange in designer or using code:
this.AutoValidate = System.Windows.Forms.AutoValidate.EnableAllowFocusChange;
Code for Validation:
private void txtFirstname_Validating(object sender, CancelEventArgs e)
{
if (string.IsNullOrEmpty(this.txtFirstname.Text))
{
this.errorProvider1.SetError(this.txtFirstname, "Some Error");
e.Cancel = true;
}
else
{
this.errorProvider1.SetError(this.txtFirstname, null);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
if (this.ValidateChildren())
{
//Here the form is in a valid state
//Do what you need when the form is valid
}
else
{
//Show error summary
}
}

Showing a messagebox the moment the user clicks out of the textbox

I have currently set it up such that when a button is pressed and the textbox value is incorrect, it shows a messagebox. It is ok when I am testing only one textbox but when I want to test more than 1 textbox, it becomes messy where multiple messageboxes starts appearing.
Is there a way I can set it up such that the messagebox flashes the moment the user clicks away from the textbox.
For example I am expecting the textbox text to be 'World' and the user fills in the textbox with the text "hello". After that, the use goes on to click into the next textbox. When he does that the messagebox appears.
I have conflicting thoughts on this cos user could click 'x' on the messagebox and go to click the 3rd textbox which will prompt the messagebox again causing annoyance. Would be great if I could get some advice on maybe a better way to do this.
In total I am having 3 textboxes all needing to be filled and I want to check if there is any invalid entry for each of them. I tried touchleave event but it is not working. Thanks for help.
private void Button_Click(object sender, RoutedEventArgs e)
{
name = textbox_Name.Text;
if (name != "World")
{
MessageBox.Show("Invalid Entry for name.");
}
age = textbox_age.Text;
if (age != "World")
{
MessageBox.Show("Invalid Entry for age.");
}
gender = textbox_gender.Text;
if (gender != "World")
{
MessageBox.Show("Invalid Entry for gender.");
}
}
Change the logic to something that only produces one message box when the button is clicked. You could display the issue with the input in that box, maybe if name and age are wrong you could list both problems. It just requires some extra logic somewhere. I don't know what logic you need, but below is a simple example that shows a non-specific validation error.
private void Button_Click(object sender, RoutedEventArgs e)
{
name = textbox_Name.Text;
age = textbox_age.Text;
gender = textbox_gender.Text;
if (gender != "World" || name != "World" || age!="World" )
{
MessageBox.Show("Invalid Entry.");
}
}
As far as the TextChanged event goes, I'd recommend highlighting it on TextChanged, as suggested in a comment above. It's less annoying for your users. Then you could show a single MessageBox if the user clicks the button to let them know they need to fix the red textboxes.
The easiest way would be a validation of the setter.
public string name
{ get;
set
{
if (value != "Hello")
MessageBox.Show("Blah");
else
{ name = value; }
}
}
private void button1_Click(object sender, EventArgs e)
{
name = textbox_Name.Text;
}
try using TextBox.LostFocus this way you can check each textbox after programmatically.
name = textbox_Name.Text;
age = textbox_age.Text;
gender = textbox_gender.Text;
textbox_Name.LostFocus+=delegate
{
if (name != "World")
{
MessageBox.Show("Invalid Entry for name.");
}
};
textbox_age.LostFocus+=delegate
{
if (age != "World")
{
MessageBox.Show("Invalid Entry for age.");
}
};
textbox_gender.LostFocus+=delegate
{
if (gender != "World")
{
MessageBox.Show("Invalid Entry for gender.");
}
};

How can I know which object is clicked in C#?

To make sure that the user name input is valid, I added such callback method to do the verification:
Regex UserNameRE = new Regex(#"^[a-zA-Z]\w*$");
//being called when input box is not focused any more
private void UserNameInput_Leave(object sender, EventArgs e)
{
//pop up a warning when user name input is invalid
if (!UserNameRE.IsMatch(UserNameInput.Text))
{
MessageBox.Show("Invalid User Name!");
this.UserNameInput.Text = "";
this.UserNameInput.Focus();
}
}
The method will be called when user finished their inputting(the method is bounded with the event-"leaving the input box"). It works when user left a invalid User_Name and begin to enter a password.
But it also works when user click another tab, e.g. the Register tab. I don't want this happen. Because the user obviously don't wanna login anymore if he clicks "Register" tab, and my C# app shouldnot pop up a warning box and force them inputting a valid user name again.
How can the C# tell the difference of such 2 situations? It should be easy if I know which object is being clicked.
You will have source of event in object sender in UserNameInput_Leave event.
private void UserNameInput_Leave(object sender, EventArgs e)
{
//sender is source of event here
}
Here's an option:
private void UserNameInput_Leave(object sender, EventArgs e)
{
if (sender.GetType() != typeof(TextBox))
{
return;
}
TextBox tBox = (TextBox)sender;
//pop up a warning when user name input is invalid
if (!UserNameRE.IsMatch(UserNameInput.Text) && tBox.Name == UserNameInput.Name)
{
MessageBox.Show("Invalid User Name!");
this.UserNameInput.Text = "";
this.UserNameInput.Focus();
}
}
I am not sure if there's a right solution for this particular scenario here.
When you add a handler to validate your control on mouse leave, definitely it will be executed first regardless you clicked on another control within the tab or another tab itself.
This normal flow can't be ignored easily. It must be possible by hanlding the message loop yourself but the event based flow, first leave focus, and selected index change (selecting) event will be fired. I would suggest you not to disturb the flow as the validation is client side and pretty fast. Instead of messagebox, I would recommend you to use ErrorProvider and attach to the control whenever required. Also messagebox is quite disturbing and as per your code, you're forcefully making it focus to the textbox again.
How about the following code?
public partial class Form1 : Form
{
ErrorProvider errorProvider = new ErrorProvider();
public Form1()
{
InitializeComponent();
textBox1.Validating += new CancelEventHandler(textBox1_Validating);
}
private void textBox1_Leave(object sender, EventArgs e)
{
textBox1.CausesValidation = true;
}
void textBox1_Validating(object sender, CancelEventArgs e)
{
Regex UserNameRE = new Regex(#"^[a-zA-Z]\w*$");
if (!UserNameRE.IsMatch(textBox1.Text))
{
errorProvider.SetError(this.textBox1, "Invalid username");
}
}
}

Fields validation in winforms

Is there a shortcut in validating fields in winforms? For example a particular textBox is required to be filled up before saving a record. What I always do is I check first all the required fields programatically before saving. Example:
protected bool CheckFields()
{
bool isOk = false;
if(textBox1.Text != String.Empty)
{
isOk = true;
}
return isOk;
}
private void btnSave_Click(object sender, EventArgs e)
{
if(CheckFields())
{
Save();// Some function to save record.
}
}
Is there a counter part of Validator in ASP.Net in winforms? Or any other way around...
Here is one approach:
private List<Control> m_lstControlsToValidate;
private void SetupControlsToValidate()
{
m_lstControlsToValidate = new List<Control>();
//Add data entry controls to be validated
m_lstControlsToValidate.Add(sometextbox);
m_lstControlsToValidate.Add(sometextbox2);
}
private void ValidateSomeTextBox()
{
//Call this method in validating event.
//Validate and set error using error provider
}
Private void Save()
{
foreach(Control thisControl in m_lstControlsToValidate)
{
if(!string.IsNullOrEmpty(ErrorProvider.GetError(thisControl)))
{
//Do not save, show messagebox.
return;
}
}
//Continue save
}
EDIT:
For each control in m_lstControlsToValidate you need to write the validation method that would be fired in Validating event.
ErrorProvider.GetError(thisControl) will return some errortext or emptystring. Empty string means the control is fine. Else the control contains some error and we abort the save operation.
We do this on all the controls in m_lstControlsToValidate. If all controls are error free we continue with save else abort.
Not really, in Win Form you should use the Control.Validating Event for validation when user is working on the form. But for saving validation You have write code that check that all data are correctly inserted by user. For instance you can create a mandatory TextBox, and iterate over all form controls looking for this type of control and check that user has inputed some text.
Use a validation control. They are the best thing to use.
Also,
protected bool CheckFields()
{
bool isOk = false;
if(textBox1.Text != String.Empty)
{
isOk = true;
}
return isOk;
}
Can be shorterned considerably to:
protected bool CheckFields()
{
return textBox1.Text != String.Empty;
}

Categories