0

I need to validate 3 types using C# MVC 4 Data Annotations:

» public int Quantidade { get; set; }

Values to accept: ex. 10 all the rest need to present a custom message

» public decimal Valor { get; set; } 

Portuguese Currency ex. 10 or 10.20 all the rest need to present a custom message

» public string PesoBruto { get; set; }

Weight ex. 100 or 100.200 all the rest need to present a custom message

All of them are Required with a custom message.

Any idea?

Thanks.

Patrick
  • 2,995
  • 14
  • 64
  • 125

2 Answers2

2

I'm not sure what you're asking, whether it is to write the regular expressions for you or how to apply regular expression validation to a class property. If you need the regular expression I suggest you use this site to write one yourself (shouldn't be too difficult once you familiarize yourself with regular expressions):

http://www.regexr.com/

As for the validation part with data annotations all you have to do is decorate your model with RegularExpression attribute:

public class MyModel
{
   [Required, RegularExpression("pattern_to_match", ErrorMessage="Your custom message")]
   public string Valor { get; set; }
}

Please note that you will need to include the following namespace: System.ComponentModel.DataAnnotations

Marko
  • 12,543
  • 10
  • 48
  • 58
  • Hi, after some research, I was able to find the expression. I still have this problem now: http://stackoverflow.com/q/22067307/1480877 – Patrick Feb 27 '14 at 11:56
0
[RegularExpression(@"\d*[1-9]\d*", ErrorMessage = "Valor inválido.")]
public int Quantidade { get; set; }

Valid: 1 / 0100 / 0999 Invalid: 0 / 0.9 / 0,9

[RegularExpression(@"^(?!0\d|$)\d*(\.\d{1,2})?$", ErrorMessage = "Valor inválido.")]
public decimal Valor { get; set; } 

Valid: 01 / 0100 / 0999 / 01.00 / 1.01 Invalid: 0 / 0.900 / 0,900

[RegularExpression(@"^(?!0\d|$)\d*(\.\d{1,3})?$", ErrorMessage = "Valor inválido.")]
public string PesoBruto { get; set; }

Valid: 01 / 0100 / 0999 / 01.000 / 1.011 Invalid: 0 / 0.9001 / 0,9001

Patrick
  • 2,995
  • 14
  • 64
  • 125