开发者

Validate input field in C#

I have a input field that is supposed to take numbers only.

How can I validate the string? Would this be ok:

string s = "12345";
double num;
bool isNum = double.TryParse(s, out num);
开发者_StackOverflow社区

Or does .Net have a solution for this?


Single one line answer. Does the job.

string s = "1234";
if (s.ToCharArray().All(x => Char.IsDigit(x)))
{
    console.writeline("its numeric");
}
else
{
    console.writeline("NOT numeric");
}


What you've done looks correct.

You could also create an extension method to make it easier:

    public static bool IsNumeric(this object _obj)
    {
        if (_obj == null)
            return false;

        bool isNum;
        double retNum;
        isNum = Double.TryParse(Convert.ToString(_obj), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
        return isNum;
    }

So then you could do:

s.IsNumeric()


your solution is ok but you could create a method that does this job for you. Bear in mind it may not work for other countries because of the culture. What about something like the below?

public bool isNumeric(string val, System.Globalization.NumberStyles NumberStyle)
{
    Double result;
    return Double.TryParse(val,NumberStyle,
        System.Globalization.CultureInfo.CurrentCulture,out result);
}


VB.NET has the IsNumeric function but what you have there is the way to do that in C#. To make it available app-wide just write an extension method on string

public static bool IsNumeric(this string input)
{
    if (string.IsNullOrWhitespace(input))
        return false;

    double result;
    return Double.TryParse(input, out result);
}


You can use Regular Expression Validators in ASP.NET to constrain the input.


Why don't you try to validate the input through the UI? I don't know if you're using asp.net, if so, the RegularExpressionValidator is normally a valid solution for this. (http://www.w3schools.com/aspnet/control_regularexpvalidator.asp). Hope this helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜