AdventureWorks.WebServices.Models.Address.ValidateZipCodeState C# (CSharp) Метод

ValidateZipCodeState() публичный статический Метод

public static ValidateZipCodeState ( object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext ) : System.ComponentModel.DataAnnotations.ValidationResult
value object
validationContext System.ComponentModel.DataAnnotations.ValidationContext
Результат System.ComponentModel.DataAnnotations.ValidationResult
        public static ValidationResult ValidateZipCodeState(object value, ValidationContext validationContext)
        {
            bool isValid = false;
            try
            {
                if (value == null)
                {
                    throw new ArgumentNullException("value");
                }

                if (validationContext == null)
                {
                    throw new ArgumentNullException("validationContext");
                }
                
                var address = (Address)validationContext.ObjectInstance;

                if (address.ZipCode.Length < 3)
                {
                    return new ValidationResult(Resources.ErrorZipCodeInvalidLength);
                }

                string stateName = address.State;
                State state = new StateRepository().GetAll().FirstOrDefault(c => c.Name == stateName);
                int zipCode;
                Int32.TryParse(address.ZipCode.Substring(0, 3), out zipCode);
                if (zipCode == 0)
                {
                    //Only supporting numeric zip codes.
                    return new ValidationResult(Resources.ErrorInvalidZipCodeInState);
                }

                foreach (var range in state.ValidZipCodeRanges)
                {
                    // If the first 3 digits of the Zip Code falls within the given range, it is valid.
                    int minValue = Convert.ToInt32(range.Split('-')[0], CultureInfo.InvariantCulture);
                    int maxValue = Convert.ToInt32(range.Split('-')[1], CultureInfo.InvariantCulture);

                    isValid = zipCode >= minValue && zipCode <= maxValue;

                    if (isValid) break;
                }
            }
            catch (ArgumentNullException)
            {
                isValid = false;
            }

            if (isValid)
            {
                return ValidationResult.Success;
            }
            else
            {
                return new ValidationResult(Resources.ErrorInvalidZipCodeInState);
            }
        }
    }