Link to home
Start Free TrialLog in
Avatar of ksd123
ksd123

asked on

Decimal validation using c#

Hi Experts,

I am doing Model validation in web api and have to validate decimal field using C#.

Valid inputs: 3.00,38, 498, 4444.4
Invalid inputs: @@,##,3.#d

Here is the code
 public class Foo
    {
       
      [Required(ErrorMessage = "Price is required")]
        
        public decimal Price { get; set; }
       
    }

if(this.Price>=777.77m)
{

return new ValidationResult("Price can't be greater than 777.77")

}

Open in new window

//Want to check if input is decimal or not .How can I achieve using c# .Do we have any built-in function in c#?

else if (!input is decimal )
{
return new ValidationResult("Invalid Price fomat")
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Kyle Abrahams, PMP
Kyle Abrahams, PMP
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Rgonzo1971
Rgonzo1971

Hi,

Maybe Decimal.TryParse
string value;
decimal number;

// Parse a floating-point value with a thousands separator. 
value = "1,643.57";
if (Decimal.TryParse(value, out number))
   Console.WriteLine(number);
else
   Console.WriteLine("Unable to parse '{0}'.", value);  

Open in new window


Refer to http://msdn.microsoft.com/en-us/library/9zbda557(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1

Regards
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ksd123

ASKER

Hi Kyle,

I tried below code as you suggested,but giving error "invalid arguements".

decimal.TryParse takes string and decimal types as agruments.

Decimal d;

if (!decimal.TryParse(this.Price, out d))
  return new ValidationResult("Invalid Price fomat");
TryParse is for attempting to turn strings into decimals, not decimals into decimals. This is why you get the error. Please see my previous comment.