1

I have one property as Year01. I have decorated the same to take only decimal numbers. But it breaks as soon as it get value as -15 (minus fifteen).
How to rectify this?

[RegularExpression(@"^\s*?([\d\,]+(\.\d+)?|\.\d+)\s*$", ErrorMessage = "Only decimal numbers are allowed")]
public string YEAR01 { get; set; }

Thanks.

VMAtm
  • 27,943
  • 17
  • 79
  • 125
Bokambo
  • 4,204
  • 27
  • 79
  • 130
  • 2
    Why are you using `string` type if you are using that to store decimal value ? What is wrong with using `decimal` type ? – Shyju Sep 12 '16 at 18:33
  • I cannot use it...I am fixing somebody else code...I dont know why he took string...my mind also raised why not decimal over string ? – Bokambo Sep 12 '16 at 18:39

1 Answers1

0

Let's take a look at the regex you are using:

^\s*?([\d\,]+(\.\d+)?|\.\d+)\s*$

First symbol is ^, which stands for a start of a line. \s is a space symbol, * says this symbol can occur many times, ? symbol stands for a 0 or greater space occurrences. So this group of symbols simply cuts out the whitespace at the line start.

The similar sequence can be found at the end of the regex, it goes without ? sign, which, as I think, can be copied to the left side of your regex, and $ stands for a line ending.

In between of this space-cutting constructs you may find the main checking for a numeric string, which says that number can contain any sequences of digits and thousand separator ([\d\,]+ says that we are searching for a one or greater number of occurrences for digit with trailing thousand separator) after which we can or can not find the decimal separator and digits after it.

So, the change you want to do is quite simple, you only have to add check for a - sign with question mark at the start of the main symbol group, like this:

^\s*?(-?[\d\,]+(\.\d+)?|\.\d+)\s*$

You can find more useful regex samples here.

Community
  • 1
  • 1
VMAtm
  • 27,943
  • 17
  • 79
  • 125