如何在当前代码中添加数据验证?

时间:2016-05-24 12:02:03

标签: c# winforms

我100%新编程,这就是我想要的:

  • (姓名)无数字
  • (卡号)限制为16位且无字母
  • (到期日)这样的数字 - " 02/17"没有信件
  • (安全代码)限制为3个数字而不是字母。

我的代码:

string message =
    "Name: " + nameTextBox.Text +
    "\nCard Number: " + cardNumberTextBox.Text +
    "\nExpiry Date: " + expiryDateTextBox.Text +
    "\nSecurity Code: " + securityCodeTextBox.Text +
    "\nOrder: Pizza " + pizzaType + ", " + pizzaSize;

if (TotalToppingQuantities() > 0)
{
    for (int toppingIndex = 0; toppingIndex < toppingQuantities.Length; toppingIndex++)
    {
        if (toppingQuantities[toppingIndex] > 0)
        {
            message += ", " + toppingQuantities[toppingIndex] + " x " +
                       toppingNames[toppingIndex];
        }
    }
}

message +=
    "\nPickup Spot: " + pickupSpot +
    "\nDelivery Time: 30 minutes";

MessageBox.Show(message);

1 个答案:

答案 0 :(得分:2)

对于您的问题,regex是一个很好的解决方案。

这应该对你有用

using System.Text.RegularExpressions;
//====================================


if (Regex.Match(nameTextBox.Text, "\\d").Success) 
{
    MessageBox.Show("(Name) must contain No numbers");
    return ;
}
if (!Regex.Match(cardNumberTextBox.Text, "^\\d{16}$").Success) 
{
    MessageBox.Show("(Card Number) must be Limited to 16 digits and no letters");
    return ;
}
if (!Regex.Match(expiryDateTextBox.Text, "^\\d{2}/\\d{2}$").Success) 
{
    MessageBox.Show("(Expiry Date) must be Numbers like this - 02/17 and no letters");
    return ;
}
if (!Regex.Match(securityCodeTextBox.Text, "^\\d{3}$").Success) 
{
    MessageBox.Show("(Security Code) must be Limited to 3 numbers and no letters.");
    return ;
}