using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.ComponentModel.DataAnnotations; using Sleis.Validation.Attribute; using Sleis.Models; using Sleis.ViewModels; using Sleis.Utility; using System.Text.RegularExpressions; namespace Sleis.Validation { public static class CustomFieldValidator { public static List Validate(SleisViewType viewType, List fields) { if (viewType == SleisViewType.Undefined) { throw new ArgumentOutOfRangeException("View type not set"); } ArgumentValidationUtility.ThrowOnNull(fields, "Custom Fields"); List errors = new List(); if (fields != null) { for (int i = 0; i < fields.Count; i++) { CustomFieldView fieldView = fields[i]; if (fieldView.Field == null || fieldView.Value == null) { throw new ArgumentOutOfRangeException("CustomFieldView not properly configured"); } //Public Required if (viewType == SleisViewType.Public) { if (fieldView.Field.PublicStyle == CustomFieldDataStyleType.Required && fieldView.ValueIsNullOrEmpty) { errors.Add(new ValidationResult(Constants.RequiredErrorMessage, GetMemberName(i))); continue; } }//Public Required //If it has data, make sure it is of the right type if (!fieldView.ValueIsNullOrEmpty) { switch (fieldView.Field.Type) { case CustomFieldDataType.Boolean: if (fieldView.Value.FieldValue.Value != "Y" && fieldView.Value.FieldValue.Value != "N") { errors.Add(new ValidationResult("Invalid Boolean Format", GetMemberName(i))); continue; } break; case CustomFieldDataType.Date: DateTime testDate = DateTime.MinValue; if (!DateTime.TryParse(fieldView.Value.FieldValue.Value, out testDate)) { errors.Add(new ValidationResult("The format is invalid", GetMemberName(i))); continue; } else { fieldView.Value.FieldValue.Value = testDate.ToString("yyyy-MM-dd"); } break; case CustomFieldDataType.Numeric: decimal testNumber = Decimal.MinValue; if (!Decimal.TryParse(fieldView.Value.FieldValue.Value, out testNumber)) { errors.Add(new ValidationResult(Constants.InvalidNumericValueErrorMessage, GetMemberName(i))); continue; } break; default: break; } //switch //If we are still in the game, let's check the regex //TODO: Check if the requirement for all RegEx to start with the pattern escape will work if (!String.IsNullOrEmpty(fieldView.Field.FormatExpression) && fieldView.Field.FormatExpression.StartsWith("^")) { Regex re = new Regex(fieldView.Field.FormatExpression, RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); if (!re.IsMatch(fieldView.Value.FieldValue.Value)) { errors.Add(new ValidationResult(Constants.FormatErrorMessage, GetMemberName(i))); continue; } } }// not empty } } return errors; } private static IEnumerable GetMemberName(int i) { return new string[] { String.Format("CustomFields[{0}]", i) }; } } }