Inheritance: ConfigurationValidatorBase
        private bool CheckMailAddressValid(string mailAddress)
        {
            bool valid = false;
              try
              {
            if (mailAddress != null && mailAddress.Length > 0)
            {
              // check email format
              RegexStringValidator validator = new RegexStringValidator("^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,3}$");
              try
              {
            validator.Validate(mailAddress);
            valid = true;
              }
              catch (ArgumentException ae)
              {
            //throw new Exception(string.Format("[{0}] Reason: {1}", mailAddress, ae.Message));
            throw new Exception();
              }
            }
            else
              throw new Exception();
              }
              catch (Exception e)
              {
            SetControlBasedOnEmailValidity(false);
              }

              return valid;
        }
		public void IllegalRegex ()
		{
			RegexStringValidator v = new RegexStringValidator ("[0-9+");

			v.Validate ("123456");
			v.Validate ("123457");
		}
		public void CanValidate ()
		{
			RegexStringValidator v = new RegexStringValidator ("[0-9]+");

			Assert.IsTrue (v.CanValidate (typeof (string)));
			Assert.IsFalse (v.CanValidate (typeof (int)));
			Assert.IsFalse (v.CanValidate (typeof (object)));
		}
		public void Match_succeed ()
		{
			RegexStringValidator v = new RegexStringValidator ("[0-9]+");

			v.Validate ("123456789");
			v.Validate ("1234567");
			v.Validate ("12345");
		}
Example #5
0
 /// <summary>
 /// Visitor pattern style method - validates the value of the given element
 /// </summary>
 /// <param name="e">Element</param>
 /// <returns>is valid</returns>
 public bool validate(CMS_Form_Element e)
 {
     try {
         RegexStringValidator v = new RegexStringValidator("[a-zA-Z.-_]+@[a-zA-Z.-_].[a-zA-Z]{2,4}");
         v.Validate(e.getValue());
     }
     catch(Exception )
     {
         e.addValidationError("The given value is not a valid e-mail address");
         return false;
     }
     return true;
 }
        /// <summary>
        /// Visitor pattern style method - validates the value of the given element
        /// </summary>
        /// <param name="e">Element</param>
        /// <returns>is valid</returns>
        public bool validate(CMS_Form_Element e)
        {
            RegexStringValidator r = new RegexStringValidator("[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}");

            bool result = true;

            try
            {
                r.Validate(e.getValue());

                string[] vals = e.getValue().Split(' ');
                string[] date = vals[0].Split('-');

                int year = int.Parse(date[0]);
                int month = int.Parse(date[1]);
                if (month > 12) result = false;
                int day = int.Parse(date[2]);

                if (month == 2 && (year % 4 == 0) && day > 29) result = false;
                if (month == 2 && (year % 4 != 0) && day > 28) result = false;

                if (month < 8 && (month % 2 == 0) && day > 30) result = false;
                if (month < 8 && (month % 2 == 1) && day > 31) result = false;

                if (month > 7 && (month % 2 == 0) && day > 31) result = false;
                if (month > 7 && (month % 2 == 0) && day > 31) result = false;

                string[] time = vals[1].Split(':');

                int hour = int.Parse(time[0]);
                if (hour > 24) result = false;

                int minute = int.Parse(time[1]);
                if (minute > 60) result = false;

                int second = int.Parse(time[2]);
                if (second > 60) result = false;
            }
            catch (ArgumentException)
            {
                result = false;
            }

            if (result == false)
            {
                e.addValidationError("The given value doesn't match the datetime pattern YYYY-MM-DD HH:mm:ss");
            }

            return result;
        }
Example #7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            RegexStringValidator rsv = new RegexStringValidator(@"^[1-9]\d*$");

            try
            {
                rsv.Validate(Request.QueryString["id"].Trim());
                myUser = UserManage.GetItem(Convert.ToInt32(Request.QueryString["id"]));

                this.tbxNewPass.Enabled = true;
                this.tbxOldPass.Enabled = true;
                this.tbxCfmPass.Enabled = true;
                this.btnConfirm.Enabled = true;

                this.lblUser.Text = myUser.UserName;
            }
            catch (ArgumentException ex)
            {
                this.lblError.Visible = true;
            }
        }
Example #8
0
        /*
        * Purpose : returns connestion string
        * Preconditions : app.config must be present and connect connection string must exists
        * Postconditions : Exception
        * Input parameters : None
        * returns : Connection string validated
        * Date created : 06.07.2015
        * Date last changed : 06.07.2015
        * Author (e-mail) : Matea [email protected]
        */
        private static string getConnString()
        {
            string connInfo = String.Empty;
            const string regex = @"((.*(server|user id|password|database)=[^=;]*;){4})";

            try
            {
                connInfo = ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
                RegexStringValidator r = new RegexStringValidator(regex);
                r.Validate(connInfo);
            }
            catch (ArgumentException e)
            {
                throw new ArgumentException("The connection string is not valid!");
            }
            catch(Exception ex)
            {
                throw new ArgumentException("Connection String connect was not found in app.config! Execution aborted");
            }

            return connInfo;
        }
        private List<TicketEventNotification> CreateNotesForUsers(Dictionary<string, string> userReasons, TicketComment comment)
        {
            List<TicketEventNotification> newNotes = new List<TicketEventNotification>();
            var dt = DateTime.Now;
            foreach (var userReason in userReasons)
            {
                var note = new TicketEventNotification();
                note.CreatedDate = dt;
                note.EventGeneratedByUser = comment.CommentedBy;

                //validate email address, if not valid we'll queue the note but not bother sending it (and having to go through the retries)
                bool emailValid = false;
                string email = Security.GetUserEmailAddress(userReason.Key);
                var rxv = new RegexStringValidator(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
                try
                {
                    rxv.Validate(email);
                    emailValid = true;
                }
                catch { }

                note.NotifyEmail = (emailValid && !string.IsNullOrEmpty(email)) ? email : "invalid";
                note.NotifyUser = userReason.Key;
                note.NotifyUserDisplayName = Security.GetUserDisplayName(userReason.Key);
                note.NotifyUserReason = userReason.Value;
                newNotes.Add(note);
            }
            return newNotes;
        }
		public void Match_fail ()
		{
			RegexStringValidator v = new RegexStringValidator ("[a-z]+");

			v.Validate ("1234");
		}
Example #11
0
        /// <summary>
        /// Formats date from d.m.Y H:i:s to Y-m-d H:i:s
        /// </summary>
        /// <param name="str">date</param>
        /// <returns>date</returns>
        public static string reFormatDate(string str)
        {
            RegexStringValidator r = new RegexStringValidator("[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}");

            try
            {
                r.Validate(str);
            }catch
            {

                string[] vals = str.Split(' ');

                string[] date = vals[0].Split('.');
                string[] time = vals[1].Split(':');

                string month = (date[1].Length == 2 ? date[1] : "0" + date[1]);
                string day = (date[0].Length == 2 ? date[0] : "0" + date[0]);

                return date[2] + "-" + month + "-" + date[0] + " " + vals[1];

            }

            return str;
        }
        //public JsonResult GetEmpresas(int empresaId)
        //{
        //    var empresas =
        //        from empresa in db.Empresas
        //        where empresa.Id == empresaId
        //        select new { Id = empresa.Id, Descripcion = empresa.Nombre };
        //    return Json(empresas.ToList(), JsonRequestBehavior.AllowGet);
        //}
        //[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
        public ActionResult ValidateEmailList(string Emails)
        {
            var returnValue = true;
            var emailRegEx = new RegexStringValidator(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
            var validEmailList = new StringBuilder();
            var emailArray = Emails.Split(';');

            foreach (var str in emailArray.Where(str => !string.IsNullOrEmpty(str)))
            {
                try
                {
                    emailRegEx.Validate(str);
                    validEmailList.Append(str);
                    validEmailList.Append(";");
                }
                catch (ArgumentException)
                {
                    returnValue = false;
                    break;
                }
            }

            return Json(returnValue, JsonRequestBehavior.AllowGet);
        }
Example #13
0
        private bool ValidatePage(String itemIDString, List<int> pageIDs, String emailAddress,
            String shareWith, out int itemID)
        {
            bool valid = true;

            this._errMsg = String.Empty;

            if (!Int32.TryParse(itemIDString, out itemID))
            {
                valid = false;
                this._errMsg += "<br/>No valid item identifier.";
            }

            if (pageIDs.Count == 0)
            {
                valid = false;
                this._errMsg += "<br/>Please specify a range of pages images or select individual page images.";
            }

            if (emailAddress == String.Empty)
            {
                valid = false;
                this._errMsg += "<br/>Please enter an email address.";
            }
            else
            {
                RegexStringValidator validator = new RegexStringValidator("\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
                try
                {
                    validator.Validate(emailAddress);
                }
                catch
                {
                    valid = false;
                    this._errMsg += "<br/>Please enter a valid email address.";
                }
            }

            if (shareWith != String.Empty)
            {
                String[] shareWithAddresses = shareWith.Split(',');

                foreach (String shareWithAddress in shareWithAddresses)
                {
                    RegexStringValidator validator = new RegexStringValidator("\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
                    try
                    {
                        validator.Validate(shareWithAddress.Trim());
                    }
                    catch
                    {
                        valid = false;
                        this._errMsg += "<br/>Make sure that all email addresses are valid.";
                        break;
                    }
                }
            }

            return valid;
        }
Example #14
0
        /**************************************************************************************************************************
         * Author: Ryan Causey
         * Created: 4/3/13
         * Function to validate a string against the given regex.
         * @Return: True = the string is valid, False = the string is not valid
         * @Params: Regex = the regular expression by which to evaluate the string
         * stringToValidate = the string which we will validate against the regex
         * Last Edited By:
         * Last Edited Date:
         **************************************************************************************************************************/
        private bool validateTheString(String regex, String stringToValidate)
        {
            RegexStringValidator validator = new RegexStringValidator(regex);

            try
            {
                validator.Validate(stringToValidate);
            }
            catch (ArgumentException)
            {
                return false;
            }

            return true;
        }
 public RegexStringWrapperValidator(string regex, int minLength,
                                    int maxLength)
 {
     m_regexValidator = new RegexStringValidator(regex);
     m_stringValidator = new StringValidator(minLength, maxLength);
 }
Example #16
0
        private TicketEventNotification CreateTicketEventNotificationForUser(int commentId, string commentBy, string user, string userType)
        {
            TicketEventNotification note = null;
            if (!string.IsNullOrEmpty(user))
            {
                bool emailValid = false;
                string email = SecurityManager.GetUserEmailAddress(user);

                // replaced pattern with variation based on the stock MS regex validator control's built-in pattern for email addresses
                //var rxv = new RegexStringValidator(@"^[a-zA-Z\.\-_]+@([a-zA-Z\.\-_]+\.)+[a-zA-Z]{2,4}$");
                var rxv = new RegexStringValidator(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
                try
                {
                    rxv.Validate(email);
                    emailValid = true;
                }
                catch { }

                note = new TicketEventNotification();
                note.TicketId = TicketId;
                note.CommentId = commentId;
                note.NotifyUser = SecurityManager.GetFormattedUserName(user);

                note.NotifyUserDisplayName = SecurityManager.GetUserDisplayName(user);
                note.NotifyUserReason = userType;
                note.EventGeneratedByUser = commentBy;
                if (!string.IsNullOrEmpty(email) && emailValid)
                {
                    note.NotifyEmail = email;
                }
                else
                {
                    note.NotifyEmail = "invalid";
                }
            }
            return note;
        }
Example #17
0
        /*********************************************************************************************
        * Author: Alejandro Sosa
        * parameters: the string to be checked
        * return type: bool to indicate success of validation
        * purpose: checks the string parameter to see if it's valid according to
        *********************************************************************************************/
        private bool photoListViewItemRenameCheck(string newName)
        {
            RegexStringValidator inputChecker = new RegexStringValidator(@"^[\w\d][\w\d ]{0,30}[\w\d]$");

            try
            {
                inputChecker.Validate(newName);
                return true;
            }
            catch (ArgumentException)
            {
                return false;
            }
        }
Example #18
0
        public bool IsKnownURIType(string filename)
        {
            bool IsURI = false;
            string expression = Properties.Settings.Default.uriRegex;
            RegexStringValidator rsv = new RegexStringValidator(expression);
            if (rsv.CanValidate(filename.GetType()))
            {
                try
                {
                    rsv.Validate(filename);
                    IsURI = true;
                    log.InfoFormat("Import.isURI: File: {0} is in URI format.", filename);
                }
                catch
                {
                    log.InfoFormat("Import.isURI: File: {0} is not in URI format.", filename);
                    IsURI = false;
                }
            }

            return IsURI;
        }
Example #19
0
        /*********************************************************************************************
        * Author: Alejandro Sosa
        * parameters: string containing the text to be checked
        * return type: bool that checks to see if input string is valid
        * purpose: checks to see if input string is valid
        *********************************************************************************************/
        private bool stringChecker(string target)
        {
            RegexStringValidator inputChecker = new RegexStringValidator(validInputKey);

            try
            {
                inputChecker.Validate(target);
            }
            catch (ArgumentException)
            {
                return false;
            }

            return true;
        }