1

How can we Validate Models passed from Views to our API Controllers in ASP.NET Core. Is there a tool like FluentValidation or any similar approach that can be customized to return our errors and messages back to the client apps?

1
  • 3
    Looks like FluentValidation is available for .NET Core? There's an example here. Commented Nov 8, 2016 at 4:58

2 Answers 2

2

You make use of the IValidatableObject interface. Then create a abstract base class and let your classes inherit from it. You will need to add a reference to System.ComponentModel.DataAnnotations. You can add helper methods to the base class as well.

public abstract class ValidatingBase : IValidatableObject
{
        public bool IsNullOrEmpty(string property)
        {
            return string.IsNullOrEmpty(property);
        }

            #region IValidatableObject

        public abstract IEnumerable<ValidationResult> Validate(ValidationContext validationContext);

        public IEnumerable<ValidationResult> Validate()
        {
            var validationErrors = new List<ValidationResult>();
            var ctx = new ValidationContext(this, null, null);
            Validator.TryValidateObject(this, ctx, validationErrors, true);
            return validationErrors;
        }

        #endregion IValidatableObject
}

Then your class that inherits from the above

public class InsertCompanies : ValidatingBase
{
   public string CompanyName { get; set; }

   #region ValidatingCommandBase

        public override IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (this.IsNullOrEmpty(this.Name))
            {
                yield return new ValidationResult($"{nameof(this.Name)} field can't be null or empty.", new[] { nameof(this.Name) });
            }

            if (this.Name?.Length > 100)
            {
                yield return new ValidationResult($"{nameof(this.Name)} field can't be greater than 100 characters.", new[] { nameof(this.Name) });
            }
        }

        #endregion ValidatingCommandBase
}

There is not much limitation as to what you can do with the above implementation. Perhaps it is a viable option for you?

Asp.Net Core gladly will call the method for you, more information can be found at the link below. https://docs.asp.net/en/latest/mvc/models/validation.html

Sign up to request clarification or add additional context in comments.

Comments

1
   [HttpPost]

    public ActionResult Register(RegisterViewModel model)
    {
  // if the validation doesn't match then load same view again with errors
        if (!ModelState.IsValid) 
        {
            return View(model);
        }



    }

1 Comment

thanks Nasim, I already know about this. I am looking for a more dynamic and customized approach using a nugget library or better way to do this.

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.