1

I have a dropdownlist named CustomerType with the the following values

Id     Name
1      Student
2      Non-Employed
3      Employed
4      SelfEmployed

and I have one more property in my viewmodel public string CompanyAddress{ get; set; }

My goal is to make CompanyAddress required if dropdownlist has values 3 or 4

I have tried the following but gets error Cannon have duplicate RequiredIf

    [RequiredIf("customerTypeID", 3, ErrorMessage = "Please enter company address")]
    [RequiredIf("customerTypeID", 4, ErrorMessage = "Please enter company address")]
    public string CompanyAddress { get; set; }
Sparky
  • 98,165
  • 25
  • 199
  • 285
ksg
  • 3,927
  • 7
  • 51
  • 97

2 Answers2

3

This will put logic in your model (which is usually a no-no), but it will work. You could change your validation to be like this:

[RequiredIf("CompanyAddressRequired", true, ErrorMessage = "Please enter company address")]

And then have a property with a getter like this:

public bool CompanyAddressRequired
{
    get
    {
        return customerTypeID == 3 || customerTypeID == 4;
    }
}
Micteu
  • 451
  • 5
  • 17
  • 1
    Any idea how this might work on front end as well? Because it throws me an error saying "Uncaught TypeError: Cannot read properties of undefined (reading 'value'). Exception occurred when checking element _ElementName_, check the 'requiredif' method." – Albos Hajdari Mar 20 '22 at 22:59
  • Oh, gosh, I haven't used this sort of validation in the last five years. Hopefully someone else can help you. Sorry. – Micteu Mar 30 '22 at 17:02
0

For the "TypeError: Cannot read properties of undefined (reading 'value')" problem, add a hidden input element on your page for that new CompanyAddressRequired property.

<input type="hidden" id="CompanyAddressRequired"/>  

I'm still working on getting the switchable field to provide validation summaries on my front end but this resolves the JS error.