Почему входы не следуют шаблонам? - PullRequest
0 голосов
/ 21 марта 2019

Я создаю приложение Windows Forms для запроса контактной информации.Я создал класс для обрезки входного текста и проверки, является ли TextBox пустым.Я также назначил шаблоны для email и phonenumber.Тем не менее, ни один из них, кажется, не работает, когда я запускаю приложение.

Форма

string quantity = string.Empty;
string name = string.Empty;
string emailpattern = string.Empty;
string phonepattern = string.Empty;

const int ContactWindow = 90;
const int SuggestedContactOffset = 3;

#region Constructors

public frmRequestContact()
{
    InitializeComponent();
}

#endregion


#region Event Handlers

private void frmRequestContact_Load(object sender, EventArgs e)
{
    //initialize contact date control
    dtpContactDate.MaxDate = DateTime.Today.AddDays(ContactWindow);
    dtpContactDate.MinDate = DateTime.Today;
    dtpContactDate.Value = DateTime.Today.AddDays(SuggestedContactOffset);

    //initialize contact method control
    rbEmail.Checked = true;
}   

private void btnContact_Click(object sender, EventArgs e)
{
    // Input variables
    string quantity = string.Empty;
    string name = string.Empty;
    string emailpattern = @"^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,}$";
    string phonepattern = @"^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$";

    // Contact Date
    DateTime contactDate = DateTime.MinValue;

    // Contact Method
    ContactMethod method = ContactMethod.Unassigned;

    // Gather inputs
    if (GetContactDate(ref contactDate) 
        && GetContactMethod(ref method) 
        && GetEmail(ref emailpattern) 
        && GetName(ref name) 
        && GetQuantity(ref quantity) 
        && GetPhone(ref phonepattern))
    {
        // Submit contact request and close the form
        string format = "Your contact request has been entered.\n\n" 
            + "Quantity: {0}\n" 
            + "Name: {1}\n" 
            + "Email: {2}\n" 
            + "Phone: {3}\n" 
            + "Contact Date: {4:D}\n" 
            + "Contact Method: {5}\n";

        string msg = string.Format(format, quantity, name, emailpattern, phonepattern, contactDate, method);
        MessageBox.Show(msg, Application.ProductName);

        Close();
    }
}

private void TextBox_Leave(object sender, EventArgs e)
{
    TextBox tb = (TextBox)sender;
    Input.TrimText(tb.Text);
}

#endregion


#region Input

private bool GetQuantity(ref string quantity)
{
    bool success = true;
    try
    {
        Input.TrimText(txtQuantity.Text);
        if (Input.IsTextEmpty(txtQuantity.Text))
            throw new InputRequiredException();
        quantity = txtQuantity.Text;

        return success;
    }
    catch (Exception error)
    {
        string remediation = "Enter quantity.";
        Input.ShowError(error, remediation);
        Input.SelectText(txtQuantity);
    }
    return success;
}

private bool GetName(ref string name)
{
    bool success = true;
    try
    {
        Input.TrimText(txtName.Text);//removing whitespace
        if (Input.IsTextEmpty(txtName.Text))//checking if the input is empty, if so throw new exception
            throw new InputRequiredException();
        name = txtName.Text;
        success = true;
    }
    catch (Exception error)
    {
        string remediation = "Enter name of individual to contact.";
        Input.ShowError(error, remediation);
        Input.SelectText(txtName);
    }
    return success;
}

private bool GetEmail(ref string emailpattern)
{
    bool success = true;
    try
    {
        Input.TrimText(txtEmail.Text); //removing whitespace
        if (Input.IsTextEmpty(txtEmail.Text))
            throw new InputRequiredException();
        emailpattern = txtEmail.Text;
        success = true;
    }
    catch (Exception error)
    {
        string remediation = "Enter a valid email.";
        Input.ShowError(error, remediation);
        Input.SelectText(txtEmail);
    }
    return success;
}

bool GetPhone(ref string phonepattern)
{
    bool success = true;
    try
    {
        Input.TrimText(txtPhone.Text);
        if (Input.IsTextEmpty(txtPhone.Text))
            throw new InputRequiredException();
        phonepattern = txtPhone.Text;
        success = true;
    }
    catch(Exception error)
    {
        string remediation = "Enter a valid phone number.";
        Input.ShowError(error, remediation);
        Input.SelectText(txtPhone);
    }
    try
    {
        int Phone = Convert.ToInt32(txtPhone.Text);
    }
    catch (Exception error)
    {
        string remediation = "Enter a valid phone number.";
        Input.ShowError(error, remediation);
        Input.SelectText(txtPhone);

    }
        return success;
}

bool GetContactDate(ref DateTime contactDate)
{
    contactDate = dtpContactDate.Value;
    return true;
}

bool GetContactMethod(ref ContactMethod method)
{
    //find selected option
    if (rbEmail.Checked)
        method = ContactMethod.Email;
    else if (rbPhone.Checked)
        method = ContactMethod.Phone;
    else if (rbEither.Checked)
        method = ContactMethod.Either;
    else //no option selected!
    {
        Showerror("Select a contact method");
        return true;
    }

    return true;
}

void Showerror(string msg)
{
    MessageBox.Show(msg, "Request Contact", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

#endregion

Входные данные

class Input
{
    static public string TrimText(string A)
    {
        return A.Trim();
    }

    internal static bool IsTextEmpty(string A)
    {
        if (string.IsNullOrEmpty(A))
        {
            return true;
        }

        else
        {
            return false;
        }
    }

    internal static void ShowError(object error, string remediation)
    {           
    }

    static public void SelectText(TextBox textBox1)
    {
         textBox1.SelectAll();
    }
}

В коде нет ошибок, и программа работает гладко, но я не получаю желаемый результат.Я абсолютный нуб, когда дело доходит до кодирования, и понимаю, что в коде могут быть логические ошибки.Если есть одна или несколько ошибок, или если код просто не завершен, пожалуйста, дайте мне знать.

1 Ответ

0 голосов
/ 21 марта 2019

Вы не пишете обрезанный текст обратно в TextBox

private void TextBox_Leave(object sender, EventArgs e)
{
    TextBox tb = (TextBox)sender;
    // Input.TrimText(tb.Text); // <-- your code
    tb .Text = Input.TrimText(tb.Text);
}

О emailpattern.В данный момент вы просто присваиваете ему значение txtEmail.Text и затем отображаете его в MessageBox.В следующем коде я удалил все и просто оставил части, где вы что-то делаете с emailpattern.

private void btnContact_Click(object sender, EventArgs e)
{
    // Input variables   
    string emailpattern = @"^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,}$";    

    if (GetEmail(ref emailpattern))
    {        
        string msg = string.Format(format, quantity, name, emailpattern, phonepattern, contactDate, method);
        MessageBox.Show(msg, Application.ProductName);
        Close();
    }
}

private bool GetEmail(ref string emailpattern)
{  
    emailpattern = txtEmail.Text;
    success = true;    
    return success;
}
...