Пример #1
0
        /// <summary>
        /// Do some basic validation. This is just a DUMMY validator
        /// to show how to incorporation the validator into the code generator.
        /// </summary>
        /// <param name="validationEvent"></param>
        /// <returns></returns>
        protected override bool ValidateInternal(ValidationEvent validationEvent)
        {
            Address            address = validationEvent.Target as Address;
            IValidationResults errors  = validationEvent.Results;
            int initialErrorCount      = errors.Count;

            if (string.IsNullOrEmpty(address.City))
            {
                errors.Add("City is empty");
            }

            if (string.IsNullOrEmpty(address.State))
            {
                errors.Add("State is empty");
            }

            if (string.IsNullOrEmpty(address.Country))
            {
                errors.Add("Country is emtpy");
            }
            else if (address.Country.Trim().ToLower() != "usa")
            {
                errors.Add("Only supports 'usa' for now.");
            }


            return(initialErrorCount == errors.Count);
        }
        /// <summary>
        /// Is valid - text doesn't contain any word that has
        /// more than maxChars specified.
        /// </summary>
        protected override bool ValidateInternal(ValidationEvent validationEvent)
        {
            object             target  = validationEvent.Target;
            IValidationResults results = validationEvent.Results;
            bool useTarget             = validationEvent.Target != null;

            string text = useTarget ? (string)target : _text;

            if (string.IsNullOrEmpty(text))
            {
                return(true);
            }

            bool isSpacerNewLine = false;
            int  currentPosition = 0;
            int  ndxSpace        = StringHelpers.GetIndexOfSpacer(text, currentPosition, ref isSpacerNewLine);

            //Check if single very long word ( no spaces )
            if (ndxSpace < 0 && text.Length > _maxCharsInWord)
            {
                results.Add(_errorMessage + _maxCharsInWord + " chars.");
                return(false);
            }

            while ((currentPosition < text.Length && ndxSpace > 0))
            {
                //Lenght of word
                int wordLength = ndxSpace - (currentPosition + 1);
                if (wordLength > _maxCharsInWord)
                {
                    results.Add(_errorMessage + _maxCharsInWord + " chars.");
                    return(false);
                }
                currentPosition = ndxSpace;
                ndxSpace        = StringHelpers.GetIndexOfSpacer(text, (currentPosition + 1), ref isSpacerNewLine);
            }

            // Final check.. no space found but check complete length now.
            if (currentPosition < text.Length && ndxSpace < 0)
            {
                //Lenght of word
                int wordLength = (text.Length - 1) - currentPosition;
                if (wordLength > _maxCharsInWord)
                {
                    results.Add(_errorMessage + _maxCharsInWord + " chars.");
                    return(false);
                }
            }
            return(true);
        }
        /// <summary>
        /// Determines if the date supplied is a date within the specified bounds.
        /// </summary>
        /// <param name="date"></param>
        /// <param name="checkMinBound"></param>
        /// <param name="checkMaxBound"></param>
        /// <param name="minDate"></param>
        /// <param name="maxDate"></param>
        /// <returns></returns>
        public static bool IsDateWithinRange(DateTime date, bool checkMinBound, bool checkMaxBound, DateTime minDate, DateTime maxDate, IValidationResults errors, string tag)
        {
            if (checkMinBound && date.Date < minDate.Date)
            {
                errors.Add(tag, "Date supplied is less than minimum date " + minDate.ToShortDateString(), null);
                return(false);
            }
            if (checkMaxBound && date.Date > maxDate.Date)
            {
                errors.Add(tag, "Date supplied is more than maximum date " + maxDate.ToShortDateString(), null);
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Determines if text supplied is numeric and within the min/max bounds.
        /// </summary>
        /// <param name="text">Text to check if it's numeric and within bounds.</param>
        /// <param name="checkMinBound">Whether or not to check</param>
        /// <param name="checkMaxBound"></param>
        /// <param name="min"></param>
        /// <param name="max"></param>
        /// <returns></returns>
        public static bool IsNumericWithinRange(double num, bool checkMinBound, bool checkMaxBound, double min, double max, IValidationResults errors, string tag)
        {
            if (checkMinBound && num < min)
            {
                errors.Add(tag, "Number supplied is less than " + min + ".", null);
                return(false);
            }

            if (checkMaxBound && num > max)
            {
                errors.Add(tag, "Number supplied is more than " + max + ".", null);
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Validate that the size is valid.
        /// </summary>
        protected override bool ValidateInternal(ValidationEvent validationEvent)
        {
            object             target  = validationEvent.Target;
            IValidationResults results = validationEvent.Results;
            bool useTarget             = validationEvent.Target != null;

            HtmlInputFile file = useTarget ? (HtmlInputFile)target : _file;

            // Validate.
            if (!ValidationUtils.Validate(file == null, results, string.Empty, _errorMessageNoFile, null))
            {
                return(false);
            }
            if (!ValidationUtils.Validate(file.PostedFile == null, results, string.Empty, _errorMessageNoFile, null))
            {
                return(false);
            }
            if (!ValidationUtils.Validate(file.PostedFile.ContentLength == 0, results, string.Empty, _errorMessageEmptyFileContent, null))
            {
                return(false);
            }

            int initialErrorCount = results.Count;

            if (_restrictSize)
            {
                int fileSizeInKiloBytes = file.PostedFile.ContentLength / 1000;

                if (fileSizeInKiloBytes > _restrictedFileSizeInKiloBytes)
                {
                    results.Add(string.Empty, "File exceeds " + _restrictedFileSizeInKiloBytes + "K.", null);
                }
            }
            return(results.Count == initialErrorCount);
        }
        /// <summary>
        /// Validate the target object( text ).
        /// </summary>
        /// <param name="target"></param>
        /// <param name="results"></param>
        /// <returns></returns>
        protected override bool ValidateInternal(ValidationEvent validationEvent)
        {
            object             target  = validationEvent.Target;
            IValidationResults results = validationEvent.Results;
            bool useTarget             = validationEvent.Target != null;

            string text = useTarget ? (string)target : _text;

            // Not required and email not supplied.
            if (!_isRequired && string.IsNullOrEmpty(text))
            {
                return(true);
            }

            int initialErrorCount = results.Count;

            bool isNullOrEmpty = string.IsNullOrEmpty(text);

            ValidationUtils.Validate(isNullOrEmpty, results, _key, _messageIfEmptyAndRequired, text);

            if (!isNullOrEmpty)
            {
                // Now check the format.
                Regex regex = new Regex(_regEx);

                if (!regex.IsMatch(text))
                {
                    results.Add(_key, _messageIfRegExFails, null);
                }
            }
            return(results.Count == initialErrorCount);
        }
 /// <summary>
 /// Check the condition and add the error.
 /// </summary>
 /// <param name="isValid"></param>
 /// <param name="errors"></param>
 /// <param name="tag"></param>
 /// <param name="error"></param>
 /// <param name="target"></param>
 /// <returns></returns>
 public static bool CheckError(bool isValid, IValidationResults errors, string tag, string error, object target)
 {
     if (!isValid)
     {
         errors.Add(tag, error, target);
     }
     return(isValid);
 }
 private ValidatorFluent IsValid(bool isValid, string error)
 {
     if (!isValid)
     {
         string prefix = string.IsNullOrEmpty(_propertyName) ? "Property " : _propertyName + " ";
         _errors.Add(prefix + error);
     }
     return(this);
 }
Пример #9
0
        /// Parses a string after validating it and returns
        /// the value of the enumeration it represents.
        /// <param name="lookup">Enumeration lookup.</param>
        /// <param name="enumType">Type of enumeration.</param>
        /// <param name="val">Value of string.</param>
        /// <param name="results">Validation results.</param>
        /// <param name="defaultValue">Default value.</param>
        /// <returns>Enumeration value.</returns>
        public static object GetValue(this EnumLookup lookup, Type enumType, string val, IValidationResults results, string defaultValue)
        {
            // Invalid enum value.
            if (!EnumLookup.IsValid(enumType, val))
            {
                results.Add("Invalid value '" + val + "' for " + enumType.Name);
                return(false);
            }

            return(EnumLookup.GetValue(enumType, val, defaultValue));
        }
        /// <summary>
        /// Determines if the date supplied is a date.
        /// </summary>
        /// <param name="text"></param>
        /// <param name="checkBounds"></param>
        /// <param name="minDate"></param>
        /// <param name="maxDate"></param>
        /// <returns></returns>
        public static bool IsDateWithinRange(string text, bool checkMinBound, bool checkMaxBound, DateTime minDate, DateTime maxDate, IValidationResults errors, string tag)
        {
            DateTime result = DateTime.MinValue;

            if (!DateTime.TryParse(text, out result))
            {
                errors.Add(tag, "Text supplied is not a valid date", null);
                return(false);
            }

            return(IsDateWithinRange(result, checkMinBound, checkMaxBound, minDate, maxDate, errors, tag));
        }
        /// <summary>
        /// Determines if text supplied is numeric and within the min/max bounds.
        /// </summary>
        /// <param name="text">Text to check if it's numeric and within bounds.</param>
        /// <param name="checkMinBound">Whether or not to check</param>
        /// <param name="checkMaxBound"></param>
        /// <param name="min"></param>
        /// <param name="max"></param>
        /// <returns></returns>
        public static bool IsNumericWithinRange(string text, bool checkMinBound, bool checkMaxBound, double min, double max, IValidationResults errors, string tag)
        {
            bool isNumeric = Regex.IsMatch(text, RegexPatterns.Numeric);

            if (!isNumeric)
            {
                errors.Add(tag, "Text supplied is not numeric.", null);
                return(false);
            }

            double num = Double.Parse(text);

            return(IsNumericWithinRange(num, checkMinBound, checkMaxBound, min, max, errors, tag));
        }
        /// <summary>
        /// Check the text for the regex pattern and adds errors in incorrect.
        /// </summary>
        /// <param name="inputText"></param>
        /// <param name="allowNull"></param>
        /// <param name="regExPattern"></param>
        /// <param name="errors"></param>
        /// <param name="tag"></param>
        /// <param name="error"></param>
        /// <param name="target"></param>
        /// <returns></returns>
        public static bool CheckErrorRegEx(string inputText, bool allowNull, string regExPattern, IValidationResults errors, string tag, string error, object target)
        {
            if (string.IsNullOrEmpty(inputText))
            {
                return(allowNull);
            }

            bool isValid = Regex.IsMatch(inputText, regExPattern);

            if (!isValid)
            {
                errors.Add(tag, error, target);
            }

            return(isValid);
        }
Пример #13
0
        /// <summary>
        /// Performs validation for creation purposes. This includes checks for duplicate usernames/emails.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="settings">The settings.</param>
        /// <param name="errors">The errors.</param>
        /// <param name="password">The password.</param>
        /// <param name="confirmPassword">The confirm password.</param>
        /// <returns>Instance of membership creation status.</returns>
        public virtual MembershipCreateStatus ValidateCreation(User user, UserSettings settings, IValidationResults errors,
                                                               string password, string confirmPassword)
        {
            MembershipCreateStatus status = MembershipCreateStatus.Success;

            // Check username
            if (!string.IsNullOrEmpty(settings.UserNameRegEx) &&
                !Regex.IsMatch(user.UserName, settings.UserNameRegEx))
            {
                status = MembershipCreateStatus.InvalidUserName;
                errors.Add("Invalid user name supplied.");
            }
            // Check email
            if (!Regex.IsMatch(user.Email, RegexPatterns.Email))
            {
                status = MembershipCreateStatus.InvalidEmail;
                errors.Add("Invalid email supplied.");
            }
            // Check password
            if (!string.IsNullOrEmpty(settings.PasswordRegEx) &&
                !Regex.IsMatch(password, settings.PasswordRegEx))
            {
                status = MembershipCreateStatus.InvalidPassword;
                errors.Add("Invalid password supplied.");
            }
            // Check passwords match
            if (string.Compare(password, confirmPassword, false) != 0)
            {
                status = MembershipCreateStatus.InvalidEmail;
                errors.Add("Password and confirm password do not match.");
            }
            // Check username duplicates
            User userExisting = Get(user.UserName);

            if (userExisting != null)
            {
                status = MembershipCreateStatus.DuplicateUserName;
                errors.Add("Username : "******" is already taken.");
            }
            // Check email duplicates
            IList <User> emailDups = this.Find("EmailLowered = '" + user.EmailLowered + "'");

            if (emailDups != null && emailDups.Count > 0)
            {
                status = MembershipCreateStatus.DuplicateEmail;
                errors.Add("Email : " + user.EmailLowered + " is already taken.");
            }
            return(status);
        }
Пример #14
0
        protected override bool ValidateInternal(ValidationEvent validationEvent)
        {
            object             target  = validationEvent.Target;
            IValidationResults results = validationEvent.Results;
            bool   useTarget           = validationEvent.Target != null;
            string fileName            = useTarget ? (string)target : _fileName;

            int initialErrorCount = results.Count;

            // Check file name was provided.
            bool isNullOrEmpty = string.IsNullOrEmpty(fileName);

            if (!ValidationUtils.Validate(isNullOrEmpty, results, string.Empty, "File not provided.", null))
            {
                return(false);
            }

            // Check that the file has an extension.
            int ndxExtensionPeriod = fileName.LastIndexOf(".");

            if (!ValidationUtils.Validate(ndxExtensionPeriod < 0, results, string.Empty, _errorMessagePrefix, null))
            {
                return(false);
            }

            // Error could occurr with file name = test. (ok for now)
            // Check for .txt extension.
            string fileExtension = fileName.Substring(ndxExtensionPeriod + 1);

            fileExtension = fileExtension.Trim().ToLower();

            // Check if valid format.
            if (!IsValidFormat(fileExtension))
            {
                results.Add(string.Empty, _errorMessagePrefix, null);
            }

            return(results.Count == initialErrorCount);
        }
        /// <summary>
        /// Validate the rule against the data.
        /// </summary>
        protected override bool ValidateInternal(ValidationEvent validationEvent)
        {
            object             target  = validationEvent.Target;
            IValidationResults results = validationEvent.Results;
            bool useTarget             = validationEvent.Target != null;

            string[] sentences         = useTarget ? (string[])target : _sentences;
            int      initialErrorCount = results.Count;

            foreach (string sentence in sentences)
            {
                if (!string.IsNullOrEmpty(sentence))
                {
                    string lowerKeyWords = sentence.ToLower();
                    if (ContainsAnySqlWords(sentence))
                    {
                        results.Add("Invalid search criteria in keywords.");
                    }
                }
            }
            return(initialErrorCount == results.Count);
        }
Пример #16
0
        /// <summary>
        /// </summary>
        /// <param name="enumType"></param>
        /// <param name="val"></param>
        /// <param name="results"></param>
        /// <returns></returns>
        public static object GetValue(this EnumLookup lookup, Type enumType, string val, IValidationResults results, string defaultValue)
        {
            // Invalid enum value.
            if (!EnumLookup.IsValid(enumType, val))
            {
                results.Add("Invalid value '" + val + "' for " + enumType.Name);
                return false;
            }

            return EnumLookup.GetValue(enumType, val, defaultValue);
        }
Пример #17
0
 /// <summary>
 /// Add a new result to the list of errors.
 /// </summary>
 /// <param name="results">Validation results.</param>
 /// <param name="key">Result key.</param>
 /// <param name="message">Result message.</param>
 protected void AddResult(IValidationResults results, string key, string message)
 {
     results.Add(key, message);
 }
Пример #18
0
 /// <summary>
 /// Add a new result to the list of errors.
 /// </summary>
 /// <param name="results"></param>
 /// <param name="key"></param>
 /// <param name="message"></param>
 /// <param name="target"></param>
 protected void AddResult(IValidationResults results, string key, string message)
 {
     results.Add(key, message);
 }
Пример #19
0
        public void OnData(string p)
        {
            try
            {
                if (package == null)
                {
                    return;
                }

                Match match = null;

                if (score == -1 && (match = RESULTS.Match(p)) != null && match.Success)
                {
                    this.score = int.Parse(match.Groups[1].Value);
                    return;
                }

                if (score != -1 && results == null)
                {
                    if (SOURCE.IsMatch(p))
                    {
                        results = new ValidationResults <SourceValidationOccurance>();
                    }
                    else if (DOWNLOAD.IsMatch(p))
                    {
                        results = new ValidationResults <DownloadStateOccurance>();
                    }

                    if (results != null)
                    {
                        results.Score = this.score;
                    }
                }



                if (results is ValidationResults <DownloadStateOccurance> &&
                    package.ContainsKey(typeof(DownloadData)) &&
                    (match = DOWNLOAD.Match(p)) != null && match.Success)
                {
                    String url = match.Groups[1].Value;

                    DownloadData  dd = package[typeof(DownloadData)] as DownloadData;
                    DownloadState ds = null;

                    if (dd != null)
                    {
                        foreach (DownloadState d in dd)
                        {
                            if (String.IsNullOrEmpty(d.URL) == false && d.URL.Equals(url))
                            {
                                ds = d;
                                break;
                            }
                        }
                    }

                    if (ds != null)
                    {
                        results.Add(new DownloadStateOccurance(ds));
                    }
                }
                else if (results is ValidationResults <SourceValidationOccurance> &&
                         (package.ContainsKey(typeof(BrokenSourceData)) || package.ContainsKey(typeof(PageSourceData))) &&
                         (match = SOURCE.Match(p)) != null && match.Success)
                {
                    PageSourceData psd = null;

                    if (package.ContainsKey(typeof(BrokenSourceData)))
                    {
                        psd = (PageSourceData)package[typeof(BrokenSourceData)];
                    }

                    if (psd == null && package.ContainsKey(typeof(PageSourceData)))
                    {
                        psd = (PageSourceData)package[typeof(PageSourceData)];
                    }

                    results.Add(
                        new SourceValidationOccurance(psd,
                                                      int.Parse(match.Groups[1].Value),
                                                      int.Parse(match.Groups[2].Value))
                        );
                }
            }
            catch (Exception e)
            {
                if (log.IsErrorEnabled)
                {
                    log.Error("Error parsing validator output", e);
                }
            }
        }
Пример #20
0
 /// <summary>
 /// Add a new result to the list of errors.
 /// </summary>
 /// <param name="results"></param>
 /// <param name="key"></param>
 /// <param name="message"></param>
 /// <param name="target"></param>
 protected void AddResult(IValidationResults results, string key, string message, object target)
 {
     results.Add(key, message, target);
 }