hogni89
hogni89

Reputation: 1754

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);

Or does .Net have a solution for this?

Upvotes: 2

Views: 1580

Answers (6)

Peter Marshall
Peter Marshall

Reputation: 1355

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");
}

Upvotes: 3

Peter Kelly
Peter Kelly

Reputation: 14391

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);
}

Upvotes: 1

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26737

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);
}

Upvotes: 1

aleafonso
aleafonso

Reputation: 2256

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!

Upvotes: 0

JHolyhead
JHolyhead

Reputation: 984

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

Upvotes: 0

Chris W
Chris W

Reputation: 1802

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()

Upvotes: 2

Related Questions