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
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")
}
//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")
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.Pr ice, out d))
return new ValidationResult("Invalid Price fomat");
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.Pr
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.
Maybe Decimal.TryParse
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