0

I have a model with three properties. I want to add validation logic to the TotalSalary where TotalSalary must be equal to the Sum of BasicSalary And AllowanceSalary.

public class Employee
{
    [Required]
    public decimal BasicSalary{get;set;}
    [Required]
    public decimal AllowanceSalary{get;set;}
    [MyCompareAttribute]
    public decimal TotalSalary{get;set;}
}

public class MyCompareAttribute: ValidationAttribute
{
    // I have no idea how to do this
}
demo
  • 6,038
  • 19
  • 75
  • 149
Anuj Tamrakar
  • 81
  • 2
  • 9
  • 2
    do you really need this validation? you can just calculate `TotalSalary` based on 2 values of `BasicSalary` and `AllowanceSalary` – demo May 15 '19 at 09:42
  • Possible duplicate of [Custom validation attribute that compares the value of my property with another property's value in my model class](https://stackoverflow.com/questions/11959431/custom-validation-attribute-that-compares-the-value-of-my-property-with-another) – demo May 15 '19 at 09:44
  • yes I need. After getting the total salary , which is calculated using jquery in the UI. I will have do write some more logic. I basically need it for server side validation incase someone tries to modify total salary value using browser console. – Anuj Tamrakar May 15 '19 at 09:45
  • 1
    @demo is correct. `TotalSalary` should be a readonly property returning the sum of `BasicSalary` + `AllowanceSalary`. You can try to prevent as much hacking as you like in the UI but it doesn't stop the fact the property is always calculated. If it's calculated client side, it's calculated server side. There's no need to send the `TotalSalary` value to the server. – Brad May 15 '19 at 12:12
  • "I basically need it for server side validation incase someone tries to modify total salary value using browser console" -- That's *exactly* why it shouldn't be a posted value, in the first place. If it's calculate server-side, there's no opportunity for the user to attempt to modify it. – Chris Pratt May 15 '19 at 13:33

0 Answers0