1

My application is made on ASP.NET MVC4.And i am using MVC dataannotations validations in my viewmodel classes.

I have one decimal type column.And i am using below regular expression to validate it.

 [RegularExpression(@"^\$?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(.[0-9][0-9])?$",ErrorMessage = "Amount is invalid.")]
 public decimal Amount { get; set; }

And with the help of above regular expression its working well. But I want to add one more condition there.Which is if someone enters number like:

12.
445.

Then it should accept it and also should adds .00 means (12.00,445.00) automatically.

FYI, I have changed the above regular expression like this:

[RegularExpression(@"^\$?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(.[0-9][0-9]|.)?$",ErrorMessage = "Amount is invalid.")]

And by this its accepting the numbers like:

12.
445.

But due to MVC datatype decimal filed its giving the another validation message..

enter image description here

Can anyone suggest me how i can manage that?

1 Answer 1

1

I'd offer using shadow field:

class myModel
{
    ... 
     public decimal Amount { get; private set; }

    [RegularExpression(@"^\$?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(.[0-9][0-9])?$",ErrorMessage = "Amount is invalid.")]
    public string AmountStringed  //use this field on your form input
    {
        get { return Amount.ToString(); }
        set { Amount = decimal.parse(value); } //assign Amount
    } 
}

So you don't have to do any hacks with either client or server side valiedations

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.