验证货币文本框

Validate currency textbox

我正在使用 WinForm。我有一个文本框和一个按钮。

目标:按钮应验证文本框是否为货币格式。如果文本框是货币格式,则消息应显示货币格式。如果不是,则一条消息应显示错误格式错误。

货币格式示例:

1,234.00 美元

12,345.00 美元

123,000.00 美元

1.00 美元

更新:

这就是我所拥有的,但这是错误的。

    Private void button3_Click(object sender, EventArgs e)
    {    
        currencyTextbox = Convert.ToString(textBox4.Text);

        string money = currencyTextbox;

        string s = currencyTextbox;
        float f;
        if (float.TryParse(s, NumberStyles.AllowCurrencySymbol 
            | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands, 
            CultureInfo.GetCultureInfo("en-US"), out f))
        {
            MessageBox.Show("Ok");
        }
        else
        {
            MessageBox.Show("Wrong");
        }
     }

测试用例:

12.00 美元 - 好

12,000 美元 - 还行

$12,3,00 - 确定 -(无效)

$12,3,00# - 错误

要检查格式,您可以尝试像这样在 float 中解析它:

        string s = "3.78";
        float f;
        if (float.TryParse(s, NumberStyles.Any, CultureInfo.GetCultureInfo("en-US"), out f))
        {
            // OK
        }
        else
        {
            // WRONG
        }

试试这个,应该有用

string money = ",345.00";
float f;
if (float.TryParse(money, NumberStyles.Currency, CultureInfo.GetCultureInfo("en-US"), out f))
{
   // valid
}
else
{
    // invalid 
}

调试信息:

输出:

数字(在本例中为 decimal)与其字符串表示形式(在本例中为货币)不同。这就是为什么你必须首先从字符串的角度分析输入(是否符合格式?),然后再从数字的角度分析输入。有一些方法可以一次性执行分析(如其他答案中所建议的那样),尽管它们不能提供您所追求的决定(即,它是否是一种货币;理解为仅仅是数字是错误的)。

示例代码:

private void btn_Click(object sender, EventArgs e)
{
    //Note: ideally, curCulture shouldn't be defined here (but globally or  
    //passed as argument), but otherwise my code would be somehow incomplete.
    CultureInfo curCulture = new CultureInfo("en-US", true);

    bool isOK = false;
    string[] temp = totalTextBox.Text.Trim().Split(new string[] { curCulture.NumberFormat.CurrencySymbol }, StringSplitOptions.None);
    if (temp.Length == 2 && temp[0].Trim().Length == 0)
    {
        decimal outVal = 0m;
        if (decimal.TryParse(temp[1], out outVal)) isOK = true;
    }

    MessageBox.Show(isOK ? "currency format" : "error wrong format");

}

注意几件事:

  • curCulture 应该是你想要的格式(你甚至可以 占不同 cultures/currencies/formats)。从你的例子看来,你 想要:CultureInfo curCulture = new CultureInfo("en-US", true);.
  • 输入字符串的分析可以根据需要进行复杂的分析。例如:在发布的代码中,我还确保货币符号位于第一个位置。

----更新(解决千位分隔符的小数解析问题)

在确认所提议的 Decimal.TryParse(和其他等效方法)在涉及千位分隔符(组分隔符)时没有达到预期效果后,我决定编写下面的代码来处理这类问题。 无论如何,请记住,我在这些情况下并没有太多经验(即处理错误的十进制输入占千位分隔符),这就是为什么我不确定是否有更有效的方法来解决这个问题(尽管建议的分析当然很快)。

private void btn_Click(object sender, EventArgs e)
{
    //Note: ideally, curCulture shouldn't be defined here (but globally or  
    //passed as argument), but otherwise my code would be somehow incomplete.
    CultureInfo curCulture = new CultureInfo("en-US", true);

    bool isOK = false;
    string[] temp = totalTextBox.Text.Trim().Split(new string[] { curCulture.NumberFormat.CurrencySymbol }, StringSplitOptions.None);
    if (temp.Length == 2 && temp[0].Trim().Length == 0)
    {
        isOK = isDecimalOK(temp[1], curCulture);
    }

    MessageBox.Show(isOK ? "currency format" : "error wrong format");
}

private bool isDecimalOK(string inputString, CultureInfo curCulture)
{
    bool isOK = false;

    string[] temp = inputString.Split(new string[] { curCulture.NumberFormat.CurrencyDecimalSeparator }, StringSplitOptions.None);
    if (temp.Length > 2) return isOK;

    int outVal0 = 0;
    if (!int.TryParse(temp[0], NumberStyles.AllowThousands, curCulture, out outVal0)) return isOK;
    else if (analyseThousands(temp[0], curCulture))
    {
        isOK = (temp.Length == 2 ? int.TryParse(temp[1], NumberStyles.Integer, curCulture, out outVal0) : true);
    }

    return isOK;
}

private bool analyseThousands(string intInput, CultureInfo curCulture)
{

    string[] temp2 = intInput.Split(new string[] { curCulture.NumberFormat.CurrencyGroupSeparator }, StringSplitOptions.None);

    if (temp2.Length >= 2)
    {
        if (temp2[0].Trim().Length == 0) return false;
        else
        {
            for (int i2 = 1; i2 < temp2.Length; i2++)
            {
                if (!curCulture.NumberFormat.CurrencyGroupSizes.Contains(temp2[i2].Length)) return false;
            }
        }
    }

    return true;
}

你可以尝试使用正则表达式:

var moneyR = new Regex(@"^$(((\d{1,3},)+\d{3})|\d+)(\.\d{2}){0,1}$");
if (moneyR.IsMatch(yourValue))
{
    MessageBox.Show("Ok");
}
else
{
    MessageBox.Show("Wrong");
}