0

I want to validate models server-side in ASP.NET Core MVC:

public class Transaction
{
    [Key]
    public int Amount { get; set; }
    public int Account_Id { get; set; }
    public string Note { get; set; }
    public DateTime Date { get; set; }
}

I want to validate these attributes... like Amount cannot have negative values. But I shouldn't use model validation and data annotations, like this:

[StringLength(100)]
public string Note { get; set; }

In ASP.NET Core MVC, where and how can I validate this?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
kalpana
  • 9
  • 1
  • You can do a direct value comparison on the property in your action. Nothing fancy. But you don't get the automatic messages and UI hints. – Jasen Feb 14 '22 at 23:53
  • @jasen I can compare the value, but what if I wanted to make a field required? – kalpana Feb 15 '22 at 00:05
  • Then stop processing the normal flow (don't commit to db, for instance) and return a message indicating the status. – Jasen Feb 15 '22 at 00:19
  • 3
    Have a look at [Fluent Validation](https://docs.fluentvalidation.net/en/latest/aspnet.html). You declare the validation rules in a separate class to the model – Andrew Williamson Feb 15 '22 at 00:25
  • Why you cannot use model validation? – Yiyi You Feb 15 '22 at 02:45

0 Answers0