CustomerValidator.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. public CustomerValidator(
  26. ERPDbContext eRPDbContext,
  27. IGeocodingService geocodingService)
  28. {
  29. _eRPDbContext = eRPDbContext;
  30. _geocodingService = geocodingService;
  31. RuleFor(m => m.Firstname)
  32. .NotEmpty();
  33. RuleFor(m => m.Lastname)
  34. .NotEmpty();
  35. RuleFor(m => m.Address)
  36. .NotEmpty();
  37. RuleFor(m => m.ZipCode)
  38. .NotEmpty();
  39. RuleFor(m => m.Town)
  40. .NotEmpty();
  41. RuleFor(m => m.Country)
  42. .NotEmpty();
  43. RuleFor(m => m.Address)
  44. .Custom((a, context) =>
  45. {
  46. var model = context.InstanceToValidate as CustomerModel;
  47. if (model == null)
  48. {
  49. context.AddFailure("Unbekannter Fehler.");
  50. return;
  51. }
  52. var addressValid = _geocodingService.IsValidAddress(
  53. String.Format("{0} {1} {2}", model.Address, model.ZipCode, model.Town));
  54. if (!addressValid)
  55. {
  56. context.AddFailure("Adresse kann nicht gefunden werden. Bitte überprüfen Sie die Adresseingaben.");
  57. return;
  58. }
  59. });
  60. }
  61. #endregion
  62. }
  63. }