public void Should_have_error_when_DateUsed_is_InTheFuture() { var model = new CostItemPatchViewModel { DateUsed = DateTime.Now.AddDays(1) }; var result = validator.TestValidate(model); result.ShouldHaveValidationErrorFor(x => x.DateUsed).WhenErrorMessageContains("must be less than"); }
public void Should_have_error_when_Amount_is_Invalid() { var model = new CostItemPatchViewModel { Amount = 0.5m }; var result = validator.TestValidate(model); result.ShouldHaveValidationErrorFor(x => x.Amount).WhenErrorMessageContains("must be between 1 and 10000"); }
public void Should_have_error_when_properties_are_empty() { var model = new CostItemPatchViewModel(); var result = validator.TestValidate(model); result.ShouldHaveValidationErrorFor(x => x.ItemName); result.ShouldHaveValidationErrorFor(x => x.Amount); result.ShouldHaveValidationErrorFor(x => x.CostTypeId); result.ShouldHaveValidationErrorFor(x => x.DateUsed); }
public async Task <IActionResult> Update(Guid id, [FromBody] JsonPatchDocument <CostItemPatchViewModel> patchDocument) { { var costItem = await _costItemsRepository.GetById(id); if (costItem == null) { return(NotFound()); } var model = new CostItemPatchViewModel { Amount = costItem.Amount, ItemName = costItem.ItemName, CostTypeId = costItem.CostTypeId, DateUsed = costItem.DateUsed }; patchDocument.ApplyTo(model); // auto validation by using validator if (!TryValidateModel(model)) { return(ValidationProblem(ModelState)); } // custom validation var costTypes = await _costTypesRepository.GetAll(); if (costTypes.Any(x => x.CostTypeId == model.CostTypeId) == false) { return(NotFound("CostTypeId does not exist")); } // copy the changes back to original from patched Model MapPatchedModelToCostItem(costItem, model); await _costItemsRepository.Update(costItem); return(NoContent()); } void MapPatchedModelToCostItem(CostItem costItem, CostItemPatchViewModel model) { costItem.Amount = model.Amount; costItem.CostTypeId = model.CostTypeId; costItem.ItemName = model.ItemName; costItem.DateUsed = model.DateUsed; } }