John
John

Reputation: 3945

If string contains a letter, throw error?

passing in a list of strings :

List<string> quantity

if string contains all numbers, code is fine. However if user enters a 'letter' in the quantity section and submits the code breaks.

Need to do a check in the quantity list that it does not contain letters, if so return VIEW with error message:

foreach (string q in quantity)
{
    if (q //if q == letter?)
    {
        _notifier.Information(T("A letter has been entered for quantity. Please enter a number"));

        return Redirect(returnUrl);
    }
}

How can I say is q is a letter?

thanks for any replies

Upvotes: 0

Views: 1112

Answers (4)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186813

Assuming that you accept positive integer numbers only, you should check if each string within list is not empty or null and contains anything but digits (not only letters that are 'A'..'Z', 'a'..'z' but, say '+', '{', command characters etc). You can do it by LINQ:

  // All strings within quantity contains digits only
  if (!quantity.All(c => (!String.IsNullOrEmpty(c)) && c.All(Char.IsDigit(c)))) {
    _notifier.Information(T("A letter has been entered for quantity. Please enter a number"));

    return Redirect(returnUrl);
  }

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460238

You can use Char.IsLetter, here's a short LINQ version which checks if any string contains letters:

bool anyWrong = quantity.Any(s => s.Any(Char.IsLetter));

or the opposite way, check if all are valid using Char.IsDigit:

bool allCorrect = quantity.All(s => s.All(Char.IsDigit));

Another option is to check if all strings can be parsed to int or long, e.g.:

long l;
bool allCorrect = quantity.All(s => long.TryParse(s, out l));

If you also want to allow exponential notation, you can use decimal.TryParse with NumberStyles.Float:

List<string> quantity = new List<string> { "1000000000E-100" };
decimal d;
bool allCorrect = quantity
   .All(s => decimal.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out d));

Upvotes: 7

Simon Whitehead
Simon Whitehead

Reputation: 65077

Since you have tagged this as MVC.. you should be using Data Annotations to validate your properties. E.g.:

public class YourModel {
    public IList<QuantityModel> Quantities { get; set; }
}

public class QuantityModel {
    [RegularExpression(@"\d+")] // <--- this
    public int Amount { get; set; }
}

This saves you from manually validating your properties... as you are currently attempting to do.

Upvotes: 3

Guffa
Guffa

Reputation: 700650

You can use a LINQ extension method for that:

if (!q.All(Char.IsDigit)) {
  // not only digits
}

Upvotes: 4

Related Questions