2

I have a model class and I want to make on the parameter "required" only if the value of another parameter is something.

[JsonConverter(typeof(JsonStringEnumConverter))]
[Required]
public AddressTagEnum AddressTagId { get; set; }

[RequiredIf("AddressTagId", 3)]
[MaxLength(20)]
public string AddressTagOther { get; set; }

How can I achieve this? Thanks in advance.

1 Answer 1

1

there are several ways to solve your problem:

  1. there is no standard way to do this
  2. there are librariers e.g. Expressive Annotations that should help
  3. there is a built-in attribute Remote that lets you perform a server validation like: [Remote(action: "VerifyEmail", controller: "Users")] see docs

i prefer (i know that this is opinion based) a implementation with IValidatableObject. Citing the docs:

public class ValidatableMovie : IValidatableObject
{
    private const int _classicYear = 1960;

    public int Id { get; set; }

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

    [DataType(DataType.Date)]
    [Display(Name = "Release Date")]
    public DateTime ReleaseDate { get; set; }

    [Required]
    [StringLength(1000)]
    public string Description { get; set; }

    [Range(0, 999.99)]
    public decimal Price { get; set; }

    public Genre Genre { get; set; }

    public bool Preorder { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (Genre == Genre.Classic && ReleaseDate.Year > _classicYear)
        {
            yield return new ValidationResult(
                $"Classic movies must have a release year no later than {_classicYear}.",
                new[] { nameof(ReleaseDate) });
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.