In C# how do you display an error message if both text boxes are empty? Is there a code example or validator that can be used?
You will need to use a CustomValidator.
RequiredFieldValidator should do the job?
if you want to know more about validators then look here http://www.codeproject.com/KB/validation/aspnetvalidation.aspx
if (TextBox1.Text == String.Empty && TextBox2.Text == String.Empty)
{
Label1.Text = "Your error message here";
}
else
{
//continue your logic here
}
CustomValidator gives you a callback method. You can use it like any other validator, and write the following code in the [control name]_ServerValidate method:
args.IsValid = TextBox1.Text.Length > 0 && TextBox2.Text.Length > 0;
Abstract to a scalable function:
private bool Validate(params TextBox[] boxes) {
foreach (var box in boxes)
if (string.IsNullOrEmpty(box.Text))
return false;
return true;
}
then call with
if(Validate(TextBox1, TextBox2, ...)) {
/// Do the good stuff
} else {
/// throw error
}
protected submit_click()
{
if((TextBox1.Text=="")||(TextBox2.Text==""))
{
print that error message
}
}
Related
I have this function of which works fine however is there and easier way to complete the validation check using the mail address class, and would it be more fitting. Thanks in advance.
TextBox tb = new TextBox();
tb.KeyDown += new KeyEventHandler(txtEmail_KeyDown);
string strRegex = #"^(?("")("".+?(?<!\\)""#)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])#))" + #"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))";
Regex re = new Regex(strRegex); // New regex Object created
// Run Checks after the enter is pressed.
if (e.KeyCode == (Keys.Enter))
{
// checks for is match, if empty and length
if (!re.IsMatch(txtEmail.Text) || (txtEmail.Text.Equals("")) || txtEmail.Text.Length > 100)
{
// display messagebox with error
MessageBox.Show("Email not correct format!!!! ");
}
else
{
MessageBox.Show("Email Format is correct");
}
}
}
you can validate with the EmailAddressAttribute class pretty easily like this in c#
public bool ValidateEmail(string EmailToVerify)
{
if (new EmailAddressAttribute().IsValid(EmailToVerify))
return true;
else
return false;
}
but to use this you need to add this using at the top of your c# code page
using System.ComponentModel.DataAnnotations;
the only downside to this is that EmailAdressAttribute is not so permisive so it depends on what you want to restrict and permit
And if you need it here is the link the the msdn doc about this class :
https://msdn.microsoft.com/fr-fr/library/system.componentmodel.dataannotations.emailaddressattribute(v=vs.110).aspx
No, it is not stable. Since any regular expression of itself represents a finite state machine, it can, in special cases, get into an infinite loop that grafts to the server's DDOS attack.
Just use MailAddress class for validation.
UPDATE 1
After testing MailAddress class and new EmailAddressAttribute().IsValid("MAIL_TEXT_HERE")
I came to conclusion that EmailAddressAttribute's Validation is working better.
You can implement it in this way, let's say that you have TextBox and Button for submit. Just add this Click event handler to buttons Click Event:
private void button1_Click(object sender, EventArgs e)
{
if(!new EmailAddressAttribute().IsValid(textBox1.Text))
{
MessageBox.Show("Email is not valid");
}
else
{
MessageBox.Show("Email is valid");
}
}
Can someone explain how to use TryParse in C# Visual Studio to validate some textbox. I need a function using TryParse, I have an idea but it's not working
public void Letra(TextBox caja)
{
char valor;
if(char.TryParse(caja.Text, out valor))
{
if (caja.TextLength>1)
{
caja.Text = caja.Text.Remove(caja.TextLength);
caja.SelectionStart = caja.TextLength;
}
}
}
Please see the code below.
Please note, using Javascript this could be done a lot better, but since you really want a C# function, here it is.
public bool isValid(TextBox caja)
{
string sTemp;
if (caja != null)
{
sTemp = caja.Text;
}
else
{
return false;
}
if (sTemp.Length > 0)
{
foreach (char cTemp in sTemp)
{
if (char.IsNumber(cTemp))
{
return false;
}
}
}
else
{
return false;
}
return true;
}
Regards
You can always use Regular Expression for such type of validation. It is best practice and pretty fast-
Regex charOnly=new Regex("^[^0-9]$");
You can use it in C# as you want and if your TestBox is in web form then use RegularExpressionValidator. You should refer How can I get a regex to check that a string only contains alpha characters [a-z] or [A-Z]?
You can check if your string contains numbers with following method
private bool CheckIfTextContainsNumber(string TextToCheck)
{
return Regex.IsMatch(TextToCheck, #"\d");
}
\d stands for digit (0-9) + other digits e.g. arabic
Further you code create a textbox in which you cannot type in kind of numbers by creating an EventHandler which catches the KeyPress-Event.
YourTextBoxControl.KeyPress += YourTextBoxControl_KeyPress;
Here you can check whether the char typed in is a number. If the char is a number then you set Handled to true
private void YourTextBoxControl_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = Char.IsNumber(e.KeyChar);
}
If the Password boxes are empty. It shows Passwords created Successfully. I dunno whats wrong I did here. But, if entered passwords are not matched, if condition works as per code. Error for validating null.
Code;
void savePassword(object sender, RoutedEventArgs e)
{
string password1 = createPassword.Password;
string password2 = repeatPassword.Password;
if (password1 != null || password2 != null)
{
if (password1 == password2)
{
MessageBox.Show("Password Created Successfully");
}
else
{
MessageBox.Show("Passwords did not match.");
}
}
else
{
MessageBox.Show("Both fields are required");
}
}
You can check if the PasswordBox is filled properly with the string.IsNullOrWhiteSpace or string.IsNullOrEmpty methods. Also, you might want to remove the != because your logic validates as soon as one of the PasswordBoxes has content.
Here's a sample:
//Is true only if both passwords have content
if(!string.IsNullOrWhiteSpace(password1) && !string.IsNullOrWhiteSpace(password2))
Try this
if (password1.Length == 0 || password2.Length == 0)
You have to check that password is empty or null
try this
if (!string.IsNullOrEmpty(password1) &&!string.IsNullOrEmpty(password2))
{
MessageBox.Show("Password Created Successfully");
}
else
{
MessageBox.Show("Passwords did not match.");
}
In the pursuit of elegant coding, I'd like to avoid having to catch an exception that I know well may be thrown when I try to validate that the Text field of a Textbox is an integer. I'm looking for something similar to the TryGetValue for Dictionary, but the Convert class doesn't seem to have anything to offer except exceptions.
Are there any that can return a bool for me to check?
To be clear, I'd like to avoid doing this
TextEdit amountBox = sender as TextEdit;
if (amountBox == null)
return;
try
{
Convert.ToInt32(amountBox.Text);
}
catch (FormatException)
{
e.Cancel = true;
}
in favor of something like this:
TextEdit amountBox = sender as TextEdit;
if (amountBox == null)
return;
e.Cancel = !SafeConvert.TryConvertToInt32(amountBox.Text);
Thanks!
int.TryParse is your friend...
TextEdit amountBox = sender as TextEdit;
if (amountBox == null)
return;
int value;
if (int.TryParse(amountBox.Text, out value))
{
// do something with value
e.Cancel = false;
}
else
{
// do something if it failed
e.Cancel = true;
}
... By the way, most of the privitive value types have a static .TryParse(...) method that works very similar to the sample above.
I am a MFC programmer who is new to C# and am looking for a simple control that will allow number entry and range validation.
Look at the "NumericUpDown" control. It has range validation, the input will always be numeric, and it has those nifty increment/decrement buttons.
I had to implement a Control which only accepted numbers, integers or reals.
I build the control as a specialization of (read: derived from) TextBox control, and using input control and a regular expresión for the validation.
Adding range validation is terribly easy.
This is the code for building the regex. _numericSeparation is a string with characters accepted as decimal comma values
(for example, a '.' or a ',': $10.50 10,50€
private string ComputeRegexPattern()
{
StringBuilder builder = new StringBuilder();
if (this._forcePositives)
{
builder.Append("([+]|[-])?");
}
builder.Append(#"[\d]*((");
if (!this._useIntegers)
{
for (int i = 0; i < this._numericSeparator.Length; i++)
{
builder.Append("[").Append(this._numericSeparator[i]).Append("]");
if ((this._numericSeparator.Length > 0) && (i != (this._numericSeparator.Length - 1)))
{
builder.Append("|");
}
}
}
builder.Append(#")[\d]*)?");
return builder.ToString();
}
The regular expression matches any number (i.e. any string with numeric characters) with only one character as a numeric separation, and a '+' or a '-' optional character at the beginning of the string.
Once you create the regex (when instanciating the Control), you check if the value is correct overriding the OnValidating method.
CheckValidNumber() just applies the Regex to the introduced text. If the regex match fails, activates an error provider with an specified error (set with ValidationError public property) and raises a ValidationError event.
Here you could do the verification to know if the number is in the requiered range.
private bool CheckValidNumber()
{
if (Regex.Match(this.Text, this.RegexPattern).Value != this.Text)
{
this._errorProvider.SetError(this, this.ValidationError);
return false;
}
this._errorProvider.Clear();
return true;
}
protected override void OnValidating(CancelEventArgs e)
{
bool flag = this.CheckValidNumber();
if (!flag)
{
e.Cancel = true;
this.Text = "0";
}
base.OnValidating(e);
if (!flag)
{
this.ValidationFail(this, EventArgs.Empty);
}
}
As I said, i also prevent the user from input data in the text box other than numeric characteres overriding the OnKeyPress methdod:
protected override void OnKeyPress(KeyPressEventArgs e)
{
if ((!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar)) && (!this._numberSymbols.Contains(e.KeyChar.ToString()) && !this._numericSeparator.Contains(e.KeyChar.ToString())))
{
e.Handled = true;
}
if (this._numberSymbols.Contains(e.KeyChar.ToString()) && !this._forcePositives)
{
e.Handled = true;
}
if (this._numericSeparator.Contains(e.KeyChar.ToString()) && this._useIntegers)
{
e.Handled = true;
}
base.OnKeyPress(e);
}
The elegant touch: I check if the number valid every time the user releases a key, so the user can get feedback as he/she types. (But remember that you must be carefull with the ValidationFail event ;))
protected override void OnKeyUp(KeyEventArgs e)
{
this.CheckValidNumber();
base.OnKeyUp(e);
}
You can use a regular textbox and a Validator control to control input.
Try using an error provider control to validate the textbox. You can use int.TryParse() or double.TryParse() to check if it's numeric and then validate the range.
You can use a combination of the RequiredFieldValidator and CompareValidator (Set to DataTypeCheck for the operator and Type set to Integer)
That will get it with a normal textbox if you would like, otherwise the recommendation above is good.