遍历多个文本框并验证坐标

时间:2018-09-18 11:20:42

标签: c#

我有多个文本框,要求用户以(x,y)形式输入坐标,例如5.5,7。我想同时验证x和y坐标,以确保它们是数字。我当时以为可以用逗号分割坐标并分别验证每个坐标,但是我认为那样做会很费劲吗?

private bool CoordinatesValidation()
{
    bool status = true;
    decimal temp;

    foreach (TextBox tb in pointsPanel.Controls)
    {
        if (!decimal.TryParse(tb.Text, out temp))
        {
            errorProvider1.SetError(tb, "Invalid value, please enter a number!");
            status = false;
        }
        else
        {
            errorProvider1.SetError(tb, "");
        }
    }
    return status;
}

3 个答案:

答案 0 :(得分:0)

您还可以使用正则表达式检查格式是否如下:

(\d+\.?\d+),\s*(\d+\.?\d+)

意思是:

匹配多个小数(\ d +) 与匹配。点在中间 如果有小数,请在两个小数点之间用空格匹配逗号:

https://regexr.com/3vm63

Regex regex = new Regex(@"(\d+\.?\d+),\s*(\d+\.?\d+)");
Match match = regex.Match(tb.Text);
if(!match.Success) 
{
    //append the error message
}

答案 1 :(得分:0)

您可以通过引入一个Coordinate类来利用对象定向,该类可以处理解析和验证。

此方法的优点是您可以使用其他功能扩展该类,例如通过实现IEquatable<Coordinate>IComparable<Coordinate>

public class Coordinate {

    // Hidden parameterless ctor
    private Coordinate() {}

    // Public ctor requires two numbers
    public Coordinate(decimal x, decimal y) : this() {
        X = x;
        Y = y;
    }

    public decimal? X { get; set; }
    public decimal? Y { get; set; }

    public const char AxisSeparator = ',';

    public bool IsValid() {
        return X.HasValue && Y.HasValue;
    }

    // Try to parse a coordinate text in the format "X.XX{AxisSeparator}Y.YY"
    // If the parsing is not successful, returns false and error message as out variable
    // Else returns true and the parsed Coordinate as out variable
    public static bool TryParse(string input, out Coordinate result, out string errorMessage) {
        errorMessage = string.Empty;
        result = new Coordinate();

        var parts = input.Split(AxisSeparator);
        if (parts.Count() != 2) {
            errorMessage = "Expected input in format 'X.XX, Y.YY' with '" + AxisSeparator + "' to separate X and Y coordinates.";
            return false;
        }

        decimal x;
        decimal y;
        if (!decimal.TryParse(parts[0], out x)) {
            errorMessage = "Expected input in format 'X.XX, Y.YY' with X.XX as number, but it was '" + parts[0] + "'.";
            return false;
        }

        if (!decimal.TryParse(parts[1], out y)) {
            errorMessage = "Expected input in format 'X.XX, Y.YY' with Y.YY as number, but it was '" + parts[1] + "'.";
            return false;
        }

        result = new Coordinate(x, y);
        return true;
    }

    public override string ToString() { return X.ToString() + AxisSeparator + " " + Y.ToString(); }
}

用法示例:

Coordinate coord = null;
string errorMessage = string.Empty;
var success = Coordinate.TryParse("3.14, 15.28b", out coord, out errorMessage);
if (!success) {
    Console.WriteLine("Error: " + errorMessage);
    Console.WriteLine("Coordinate is valid?: " + coord.IsValid());
}
else {
    Console.WriteLine("Success: " + coord.ToString());
}

此用法(带有字符串“ 3.14,15.28b”)将显示消息:

Error: Expected input in format 'X.XX, Y.YY' with Y.YY as number, but it was ' 15.28b'.

Coordinate is valid?: False

C# Fiddle for this example

答案 2 :(得分:0)

您是否可以遮盖文本框,以便只能输入数字或只能输入指定格式?这样一来,您就不必在事后检查它们。 https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.maskedtextbox.mask?view=netframework-4.7.2