/// <summary> /// Validation rule that checks if the target property specified in the ruleDescriptor meets the state abbreviation rule for the specified property. /// </summary> /// <param name="target">The target instance.</param> /// <param name="ruleDescriptor">The ruleDescriptor of type <see cref="StateAbbreviationRuleDescriptor" />.</param> /// <returns><c>True</c> does the target property specified in the ruleDescriptor meets the state abbreviation rule for the specified property; otherwise <c>false</c>.</returns> /// <exception cref="ArgumentException">wrong rule passed to ruleDescriptor</exception> /// <exception cref="NotSupportedException">State abbreviation validation rule can only be applied to String properties</exception> public static Boolean StateAbbreviationRule(Object target, RuleDescriptorBase ruleDescriptor) { var args = ruleDescriptor as StateAbbreviationRuleDescriptor; if (args == null) { throw new ArgumentException($"Wrong rule passed to StateAbbreviationRule {ruleDescriptor.GetType()}"); } if (args.ValidateForUnitedStatesOnly == ValidateUnitedStatesOnly.Yes) { var pi = PclReflection.GetPropertyInfo(target, "Country"); if (pi == null) { return(true); } if (Convert.ToString(pi.GetValue(target, null)) != "United States") { return(true); } } var objPi = PclReflection.GetPropertyInfo(target, args.PropertyName); if (objPi.PropertyType != typeof(String)) { throw new NotSupportedException("State abbreviation validation rule can only be applied to String properties"); } var state = Convert.ToString(objPi.GetValue(target, null)); if (args.RequiredEntry == RequiredEntry.Yes) { if (String.IsNullOrEmpty(state)) { ruleDescriptor.BrokenRuleDescription = $"{RuleDescriptorBase.GetPropertyFriendlyName(ruleDescriptor)} was null or empty but is a required field"; return(false); } } else { if (String.IsNullOrEmpty(state)) { return(true); } } if (StateAbbreviationValidator.CreateInstance().IsValid(state)) { return(true); } args.BrokenRuleDescription = $"The entered value {state} is not a valid state abbreviation"; return(false); }
/// <summary> /// Creates the instance or returns the previously created instance. /// </summary> /// <returns><see cref="StateAbbreviationValidator"/>; if not previously created will return a new instance of <see cref="StateAbbreviationValidator"/>.</returns> public static StateAbbreviationValidator CreateInstance() { return(_instance ?? (_instance = new StateAbbreviationValidator())); }