Search code examples
c#asp.net-mvcasp.net-mvc-5

I'm trying to make a label [Required] only if the condition above is true


I'm trying to make a Register page and i want to require Job details(Company name, Position, etc) part if the user is actively working. But couldn't find the solution

need condition for FirmaXXX parts


Solution

  • I would say you implement a validator in your model that looks a little like this.

    public class YourModelClassName : IValidatableObject
    {
    
      // Loads of properties Name, Phone yada yada...
    
      public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
      {
        if (EmployeeActive == true 
            && String.IsNullOrEmpty(CompanyName)
            && String.IsNullOrEmpty(Position)
            // add more if needed
           )
        {
          yield return new ValidationResult(
            // some message here.
            $"When you are an active employee you must fill in the basic data for your employment...",
            new[] { nameof(EmployeeActive) });
         }
      }
    }
    

    Read more here: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-6.0#ivalidatableobject