Search code examples
asp.net-coredata-annotationscustomvalidator

How to create a custom required if validator in asp.net core 2.1 or above


How we can create a custom model validation with both client side and server side validation in asp.net core. My requirement is to check the value of a property and if it satisfies the value, the required field should be enabled. other wise disable. The annotation can also be applied on object properties.Like this.

public class TradeModel
{   
    public bool TradingObjectives { get; set; }

    [RequiredIf("TradingObjectives","true",ErrorMessage="required")]
    public int Hedge{ get; set; }

    [RequiredIf("TradingObjectives","true",ErrorMessage="required")]
    public AddressModel Address{ get; set; }

}

public class AddressModel 
{
    public long AddressId { get; set; }

    [Required]
    public string Address1 { get; set; }

    public string Address2 { get; set; }
}

Solution

  • I think you should use Fluent Validation for custom validators. And you can add client-side support to Fluent Validation with FormHelper.

    You can write custom validators, even database queries. It's an amazing solution for you.