So I just followed a tutorial on YouTubeon how to implement a textbox validation so the user has to enter all the required fields in the correct data format. It uses System.ComponentModel.DataAnnotations and everything works great, it only has one annoying thing which is that every time the user starts writing on the textbox, they are not able to do anything else until the textbox contains the correct data format (it's not even possible to close the application when entering data in that textbox). I just wanted it to validate when clicking a button, not when entering the data. This is my class where I define the requirements for my fields:
public class SimulateValidate
{
[Required]
[Range(1, 999)]
public double XAxis { get; set; }
[Required]
[Range(1, 999)]
public double YAxis { get; set; }
[Required]
[Range(1, 99)]
public double ZAxis { get; set; }
[Required]
[Range(1, 99)]
public int Quantity { get; set; }
[Required]
public string Frame { get; set; }
[Required]
[Range(1, 99)]
public int XConfiguration { get; set; }
[Required]
[Range(1, 99)]
public int YConfiguration { get; set; }
[Required]
[Range(0, 999)]
public double Sleeve { get; set; }
[Required]
[Range(0, 999)]
public double Actuator { get; set; }
[Required]
[Range(0, 999)]
public double HBVS { get; set; }
}
And this is the implementation in a user control:
public UCSimulate()
{
InitializeComponent();
simulateValidateBindingSource.DataSource = new SimulateValidate();
}
private void bUsage_Click(object sender, EventArgs e)
{
//Validation process for the data fields.
simulateValidateBindingSource.EndEdit();
SimulateValidate simulateValidate = simulateValidateBindingSource.Current as SimulateValidate;
bool error = false;
string errorMessage = "";
if (simulateValidate != null)
{
ValidationContext context = new ValidationContext(simulateValidate, null, null);
IList<ValidationResult> errors = new List<ValidationResult>();
if (!Validator.TryValidateObject(simulateValidate, context, errors, true))
{
foreach (ValidationResult result in errors)
{
errorMessage += "- " + result.ErrorMessage + "\n";
error = true;
}
}
}
if (error)
{
MessageBox.Show("Please fill all the required fields.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
//Do stuff if the validation is correct
}
}
I thought this could be pretty simple, but after looking thorough the documentation I just get lost. The validation I'm implementing is nothing compared to everything that can be done using System.ComponentModel.DataAnnotations.