Home > Net >  How to create separated class that detect if the global int is certain number, and then overwrites l
How to create separated class that detect if the global int is certain number, and then overwrites l

Time:01-08

I want to create global class(So I have to write it only once, not in all forms )that should detect if the global int is certain number and then overwrite text in label that says what is wrong.

For example when your name is too short it will says that your name is too short. I know that you can do this in form, but I want whole new separated class because I plan to do this for 3 forms, so I would have to copy and paste the same errors etc... in each of them.

example: Code in form register_menu.cs

        public void getErrorNumber()
        {
          if (char_amount_username < 3 || textBox_username.Text == "Username")
            {
                Variables.error_number = 1;
            }
            else if (email_adress.Contains("@") != true || textBox_emailadress.Text == "Email adress")
            {
                Variables.error_number = 2;
            }
            else if (char_amount_password < 7 || textBox_password.Text == "Password")
            {
                Variables.error_number = 3;
            }
            else if (textBox_password.Text != textBox_passwordconfirm.Text)
            {
                Variables.error_number = 4;
            }
            else
            {
                Variables.error_number = 0;
            }
        }


        private void button1_Click_1(object sender, EventArgs e)
        {
            ErrorCheck();
            
        }


Code in class named GlobalErrorChecker.cs

namespace Xenious
{
     internal class ErrorVariable
    {
        public static int error_number;
        public void ErrorCheck()
             getErrorNumber();
        {
            if (ErrorVariable.error_number is 1) ;
        {
            register_menu.error_msg.Text = "Your username is invalid!\n  ⬤ Username must be avaiable\n  ⬤ Minimum lenght of username is 4 ";
            register_menu.displayERROR(true);
        }
        if(ErrorVariable.error_number is 2);
        {
            register_menu.error_message.Visible = true;
            register_menu.error_msg.Text = "Your password is invalid!\n  ⬤ Minimum lenght of password is 8 ";
            register_menu.ICON_password_error.Visible = true;
        }
        if (ErrorVariable.error_number is 6) ;
        {
            login_menu.error_message.Visible = true;
            login_menu.error_msg.Text = "Your username and password do not match!";
            login_menu.ICON_username_error.Visible = true;
            login_menu.ICON_password_error.Visible = true;
        }
     }
    }
}

This is just example code how I want to do this, I have multiple problems. First problem is that class GlobalErrorChecker.cs doesnt detect any controls from forms at all. I tried to fix this by looking online but I could find anything. Second problem is that it says register_menu.ICON_password_error is unavaiable due to protection error CS0122....

I tried quite a huge amount of different methods how to do this, but I only found how to do this between 2 diffent forms, not between form and new class

CodePudding user response:

Consider using a validation library like screenshots


First ask "what info is needed to determine a valid form?" Define these requirements in an interface:

interface IValidate
{
    // Inputs needed
    public string Username { get; }
    public string Email { get; }
    public string Password { get; }
    public string Confirm { get; }
}

Now declare an Extension Method for "any" form that implements IValidate (this is the global class you asked about).

static class Extensions
{
    public static int ValidateForm(this IValidate @this, CancelEventArgs e)
    {
        if (@this.Username.Length < 3) return 1;
        if ([email protected]("@")) return 2;
        if (@this.Password.Length < 7) return 3;
        if ([email protected](@this.Confirm)) return 4;
        return 0;
    }
}

Example of Form Validation

For each of your 3 forms, implement the interface. This just means that the 3 form classes are making a promise or contract to provide the information that the interface requires (in this case by retrieving the text from the textboxes).

public partial class MainForm : Form, IValidate
{
    #region I M P L E M E N T    I N T E R F A C E
    public string Username => textBoxUsername.Text;
    public string Email => textBoxEmail.Text;
    public string Password => textBoxPassword.Text;
    public string Confirm => textBoxConfirm.Text;
    #endregion I M P L E M E N T    I N T E R F A C E
    .
    .
    .
}

Then call the extension method when any textbox loses focus or receives an Enter key.

public partial class MainForm : Form, IValidate
{        
    public MainForm()
    {
        InitializeComponent();
        foreach (Control control in Controls)
        {
            if(control is TextBox textBox)
            {
                textBox.TabStop = false;
                textBox.KeyDown  = onAnyTextboxKeyDown;
                textBox.Validating  = onAnyTextBoxValidating;
                textBox.TextChanged  = (sender, e) =>
                {
                    if (sender is TextBox textbox) textbox.Modified = true;
                };
            }
        }
    }
    private void onAnyTextBoxValidating(object? sender, CancelEventArgs e)
    {
        if (sender is TextBox textBox)
        {
            // Call the extension method to validate.
            ErrorInt @int = (ErrorInt)this.ValidateForm(e);
            if (@int.Equals(ErrorInt.None))
            {
                labelError.Visible = false;
                buttonLogin.Enabled = true;
                return;
            }
            else if (textBox.Modified)
            {
                buttonLogin.Enabled = false;
                BeginInvoke(() =>
                {
                    switch (@int)
                    {
                        case ErrorInt.Username: textBoxUsername.Focus(); break;
                        case ErrorInt.Email: textBoxEmail.Focus(); break;
                        case ErrorInt.Password: textBoxPassword.Focus(); break;
                        case ErrorInt.Confirm: textBoxConfirm.Focus(); break;
                    }
                    labelError.Visible = true;
                    labelError.Text = typeof(ErrorInt)
                        .GetMember(@int.ToString())
                        .First()?
                        .GetCustomAttribute<DescriptionAttribute>()
                        .Description;
                    textBox.Modified = false;
                    textBox.SelectAll();
                });
            }
        }
    }
    private void onAnyTextboxKeyDown(object? sender, KeyEventArgs e)
    {
        if (sender is TextBox textbox)
        {
            if (e.KeyData.Equals(Keys.Return))
            {
                // Handle the Enter key.
                e.SuppressKeyPress = e.Handled = true;

                MethodInfo? validate = typeof(TextBox).GetMethod("OnValidating", BindingFlags.Instance | BindingFlags.NonPublic);
                CancelEventArgs eCancel = new CancelEventArgs();
                validate?.Invoke(textbox, new[] { eCancel });
            }
        }
    }
    .
    .
    .
}   

Where:

enum ErrorInt
{
    None = 0,
    [Description("Username must be at least 3 characters.")]
    Username = 1,
    [Description("Valid email is required.")]
    Email = 2,
    [Description("Password must be at least 7 characters.")]
    Password = 3,
    [Description("Passwords must match.")]
    Confirm = 4,
}
  • Related