CustomerValidator.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using FluentValidation;
  2. using GreenTree.Strohrmann.ERP.Domain.Model;
  3. using GreenTree.Strohrmann.ERP.Services.Geolocator;
  4. using GreenTree.Strohrmann.ERP.Web.Models.Business;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Data;
  8. using System.Linq;
  9. using System.Threading.Tasks;
  10. namespace GreenTree.Strohrmann.ERP.Web.Validators
  11. {
  12. public class CustomerValidator : AbstractValidator<CustomerModel>
  13. {
  14. #region DI fields
  15. // The global DbContext
  16. private readonly ERPDbContext _eRPDbContext;
  17. // The global geocoding service
  18. private readonly IGeocodingService _geocodingService;
  19. #endregion
  20. #region Ctor
  21. /// <summary>
  22. /// Initializes a new instance of the CustomerValidator class
  23. /// </summary>
  24. /// <param name="eRPDbContext">Global DbContext.</param>
  25. /// <param name="geocodingService">Global geocoding service.</param>
  26. public CustomerValidator(
  27. ERPDbContext eRPDbContext,
  28. IGeocodingService geocodingService)
  29. {
  30. _eRPDbContext = eRPDbContext;
  31. _geocodingService = geocodingService;
  32. RuleFor(m => m.Firstname)
  33. .NotEmpty();
  34. RuleFor(m => m.Lastname)
  35. .NotEmpty();
  36. RuleFor(m => m.Address)
  37. .NotEmpty();
  38. RuleFor(m => m.ZipCode)
  39. .NotEmpty();
  40. RuleFor(m => m.Town)
  41. .NotEmpty();
  42. RuleFor(m => m.Country)
  43. .NotEmpty();
  44. RuleFor(m => m.Address)
  45. .Custom((a, context) =>
  46. {
  47. var model = context.InstanceToValidate as CustomerModel;
  48. if (model == null)
  49. {
  50. context.AddFailure("Unbekannter Fehler.");
  51. return;
  52. }
  53. var addressValid = _geocodingService.IsValidAddress(
  54. String.Format("{0} {1} {2}", model.Address, model.ZipCode, model.Town));
  55. if (!addressValid)
  56. {
  57. context.AddFailure("Adresse kann nicht gefunden werden. Bitte überprüfen Sie die Adresseingaben.");
  58. return;
  59. }
  60. });
  61. }
  62. #endregion
  63. }
  64. }