SJMan
SJMan

Reputation: 1607

Validate DTO and get Error Message

I am working on a Web API2 application, need to validate the DTOs sent by the client conditionally. I am using the attribute based validation currently. The design I have is to have an IDtoValidator interface which has an IsValid() method to validate data. I need to provide the error message as well in a user readable format, which is present in the interface itself so that each class implementing the interface can put in their own error messages.

Here are my classes:

public interface IDtoValidator
{
    bool IsValid();
}

public class FormResponseDto : BaseResponseDto, IDtoValidator
{

     public bool IsValid()
     { ... some logic to validate the model...}
}

My idea of validating in the action method: Action Method:

public async Task<IHttpActionResult> MyMethod(FormResponseDto dto)
    {
         if(dto.IsValid())
            return BadRequest(dto.GetErrorMessage());
    }

Please suggest any clean design for this. The problem is that in the isValid() method i need to set the errorMessage, which is another property of the interface. which only needs to be privately set, this cannot be done in an interface.

Upvotes: 1

Views: 1168

Answers (1)

Sunil Singhal
Sunil Singhal

Reputation: 603

You can expose a Getter in your Interface like

String GetError()

or

List<String> GetErrors()

In the 2nd prototype, you may want to return an immutable collection\list so that Error(s) cannot be added into the list externally.

Upvotes: 1

Related Questions