Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

.net - C# Price Validation using regular expression other way

As part of my work,I need to read price values from Excel sheet . I need to implement

  • Prices: Non-numeric characters in Price not allowed
  • price should be valid number for price like int,decimal,double etc like 10,10.00,10,233 valid, -10,-10.00,-10,2333.00 etc are invalid
  • Prices: Price format (dots, comma's, decimals)
  • Zero and negative price values are not allowed
  • Need to check price value type (number type like int,float,decimal etc but will save in database in money format)

What datatype I should we choose for Price ? decimal or double or anyother ? In database I took database field type as money.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I do not think you need any regex if you just need to validate price numbers in C#.

I'd suggest using Decimal type, here you can find why. The Decimal class contains a static TryParse method that can be used to validate numbers as valid decimal numbers. Here is a slightly modified example from MSDN (I decided to go with InvariantCulture, but it depends on whether your DB contains currencies in EN-US format or not):

var validated = false;
decimal number;
// Parse currency value using current culture. 
var value = "1,097.63";
var style = System.Globalization.NumberStyles.Number;
var culture = System.Globalization.CultureInfo.InvariantCulture;
if (!Decimal.TryParse(value, style, culture, out number))
    if (number > 0)    // Check if the value is not negative or zero
        validated = true;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...