본문 바로가기

.NET/Winforms

[WINFORMS] Text validation

윈폼 Text 의 값의 따라 유효성을 검증하는 방법

Text 의 String 값 확인

empty

if (textBox1.Text == "")
{
    // Text is an empty string
        MessageBox.Show("alert");
        return;
}

Null check

if (string.IsNullOrEmpty(textBox1.Text))
{
    // Text is null or empty
       MessageBox.Show("alert");
       return;
}

Checking all

  • null, empty, whitespace 까지 검증
if (string.IsNullOrWhiteSpace(textBox1.Text))
{
    // Text is null, empty, or whitespace
    MessageBox.Show("alert");
    return;
}

다수의 Text 와 Combo control 를 검사

      private bool IsControlsValidation(Control container)
        {
            foreach (Control control in container.Controls)
            {
                if (control is TextBox textBox)
                {
                    if (string.IsNullOrWhiteSpace(textBox.Text))
                    {
                        //MessageBox.Show($"Please enter text in {textBox.Name}.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;
                    }
                }
                else if (control is ComboBox comboBox)
                {
                    if (comboBox.SelectedIndex == -1)
                    {
                        //MessageBox.Show($"Please select an item in {comboBox.Name}.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;
                    }
                }
            }

            return true; // All controls are valid
        }

RegExp 정규식을 이용한 검사

private bool IsRegExpValidation(TextBox textBox)
{
    string REG_EXP = @"^\d{1,10}(?:\.\d{1,5})?$";
    string text = textBox.Text;

    if (!(Regex.IsMatch(text, REG_EXP))
    {
        return false;
    }

    return true;
}

 


There might be incorrect information or outdated content.