Exemple #1
0
        /// <summary>
        /// Validation helper method
        /// </summary>
        /// <param name="node">XML node containing the validation data</param>
        /// <param name="name">The value to validate</param>
        /// <param name="errors">The list of validation errors</param>
        private void ValidateHelper(XmlNode node, string name, IList errors)
        {
            XmlNode maxLength = null;
            XmlNode regex     = null;
            string  dataValue = (this.Data[name] != null) ? this.Data[name].ToString() : null;

            // check max length
            if (dataValue != null &&
                this.data.Contains(name) &&
                ((null != (maxLength = node.SelectSingleNode("max_length"))) &&
                 (Int32.Parse(maxLength.InnerText) < dataValue.Length)))
            {
                logger.Error($"Validate error: Field [{name}] is too long. Value [{this.Data[name]}]");
                var length = Int32.Parse(maxLength.InnerText);
                errors.Add(new ValidationError(name, dataValue, length));
            }

            regex = node.SelectSingleNode("reg_ex");

            // check regular expression
            if (this.data.Contains(name) && (null != regex))
            {
                var regValidator = new RegexStringValidator(regex.InnerText);
                try
                {
                    regValidator.Validate(dataValue);
                }
                catch (System.ArgumentException sysarg)
                {
                    logger.Error($"Regexp validation failed. Field [{name}], Value [{this.Data[name]}], Pattern [{regex.InnerText}]", sysarg);
                    errors.Add(new ValidationError(name, dataValue, regex.InnerText));
                }
            }
        }
Exemple #2
0
        public static void Example7()
        {
            //The RegexStringValidator object contains the rules necessary to validate a string object based on a regular expression. The rules are established when an instance of the RegexStringValidator class is created.
            //The CanValidate method determines whether the object type being validated matches the expected type.The object being validated is passed as a parameter of the Validate method.


            // Display title.
            Console.WriteLine("ASP.NET Validators");
            Console.WriteLine();

            // Create RegexString and Validator.
            string testString  = "*****@*****.**";
            string regexString =
                @"^[a-zA-Z\.\-_]+@([a-zA-Z\.\-_]+\.)+[a-zA-Z]{2,4}$";
            RegexStringValidator myRegexValidator =
                new RegexStringValidator(regexString);

            // Determine if the object to validate can be validated.
            Console.WriteLine("CanValidate: {0}",
                              myRegexValidator.CanValidate(testString.GetType()));

            try
            {
                // Attempt validation.
                myRegexValidator.Validate(testString);
                Console.WriteLine("Validated.");
            }
            catch (ArgumentException e)
            {
                // Validation failed.
                Console.WriteLine("Error: {0}", e.Message.ToString());
            }
        }
Exemple #3
0
        public static bool Check_RepID_RegEx(string repID)
        {
            bool   check       = false;
            string regexString =
                @"^[a-zA-Z0-9]+$";
            RegexStringValidator myRegexValidator =
                new RegexStringValidator(regexString);

            // Determine if the object to validate can be validated.
            Debug.WriteLine("CanValidate: {0}",
                            myRegexValidator.CanValidate(repID.GetType()));

            try
            {
                // Attempt validation.
                myRegexValidator.Validate(repID);
                check = true;
            }
            catch (ArgumentException error)
            {
                // Validation failed.
                Debug.WriteLine("Error: {0}", error.Message);
                check = false;
            }
            return(check);
        }
Exemple #4
0
        public void IllegalRegex()
        {
            RegexStringValidator v = new RegexStringValidator("[0-9+");

            v.Validate("123456");
            v.Validate("123457");
        }
Exemple #5
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);
        }
        static void Main(string[] args)
        {
            // Display title.
            Console.WriteLine("ASP.NET Validators");
            Console.WriteLine();

            // Create RegexString and Validator.
            string testString  = "*****@*****.**";
            string regexString =
                @"^[a-zA-Z\.\-_]+@([a-zA-Z\.\-_]+\.)+[a-zA-Z]{2,4}$";
            RegexStringValidator myRegexValidator =
                new RegexStringValidator(regexString);

            // Determine if the object to validate can be validated.
            Console.WriteLine("CanValidate: {0}",
                              myRegexValidator.CanValidate(testString.GetType()));

            try
            {
                // Attempt validation.
                myRegexValidator.Validate(testString);
                Console.WriteLine("Validated.");
            }
            catch (ArgumentException e)
            {
                // Validation failed.
                Console.WriteLine("Error: {0}", e.Message.ToString());
            }

            // Display and wait
            Console.ReadLine();
        }
        /*
         *   METHOD        : paramValidations
         *   DESCRIPTION   : Checks if the user entered the correct number and type of parameters
         *   PARAMETERS    : void : Has no arguments
         *   RETURNS       : void : Has no return value
         */
        private bool paramValidation()
        {
            //Ensure they selected a service
            if (cb_WebServiceList.SelectedIndex == -1)
            {
                txt_output.Text = "Please select from the list of services...";
                return(false);
            }


            //Compare their input string to the regex pattern found in the validation file
            try
            {
                string[] validationPatterns = file.ReadAllLines(Constants.VALIDATION_FILEPATH);
                int      indexOfMethod      = GetConfigIndex();

                string regexPattern = validationPatterns.ElementAt(GetConfigIndex());
                RegexStringValidator stringValidator = new RegexStringValidator(@regexPattern);         //Light weight variant of regex class
                stringValidator.Validate(tb_param1.Text);                                               //Throws exception if regex fails
            }
            catch (Exception error)
            {
                txt_output.Text += Environment.NewLine + "ERROR: Please enter the correct amount and type of parameters...";
                Logger.RecordError(error.Message);
                return(false);
            }

            return(true);
        }
        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);
        }
Exemple #9
0
        public static bool Check_ExpirationDate_RegEx(string expirationdate)
        {
            bool   check       = false;
            string regexString =
                @"^(0[1-9]|1[012])[/](0[1-9]|[12][0-9]|3[01])[/](19|20|21)\d\d$";
            RegexStringValidator myRegexValidator =
                new RegexStringValidator(regexString);

            // Determine if the object to validate can be validated.
            Debug.WriteLine("CanValidate: {0}",
                            myRegexValidator.CanValidate(expirationdate.GetType()));

            try
            {
                // Attempt validation.
                myRegexValidator.Validate(expirationdate);
                check = true;
            }
            catch (ArgumentException error)
            {
                // Validation failed.
                Debug.WriteLine("Error: {0}", error.Message);
                check = false;
            }
            return(check);
        }
        /*
         *   METHOD        : ChecKMessageFormat
         *   DESCRIPTION   : Checks if the format of the messageTxtBox string is valid
         *   PARAMETERS    : void : Has no parameters
         *   RETURNS       : bool : True if no errors detected
         */
        private bool ChecKMessageFormat()
        {
            bool messageValid  = false;
            var  messageString = a03_ParamPanel.Controls["messageTxtBox"].Text;

            if (String.IsNullOrWhiteSpace(messageString))
            {
                //DEBUG SET LABEL TO THE RIGHT AS RED AND PRINT THE ERROR
            }
            else
            {
                try
                {
                    //Throw exception if they input any character except those found in English alphabet, and whitespace
                    RegexStringValidator stringValidator = new RegexStringValidator(@"^[a-zA-Z\s]+$");
                    stringValidator.Validate(messageString);

                    messageValid = true;
                }
                catch (Exception argEx)
                {
                    //DEBUG SET THE LABEL TO THE RIGHT OF THE TXT BOX TO INDICATE ERROR
                    Logger.RecordError(argEx.Message);
                }
            }

            return(messageValid);
        }
Exemple #11
0
        public void Match_succeed()
        {
            RegexStringValidator v = new RegexStringValidator("[0-9]+");

            v.Validate("123456789");
            v.Validate("1234567");
            v.Validate("12345");
        }
Exemple #12
0
        public void CanValidate()
        {
            RegexStringValidator v = new RegexStringValidator("[0-9]+");

            Assert.True(v.CanValidate(typeof(string)));
            Assert.False(v.CanValidate(typeof(int)));
            Assert.False(v.CanValidate(typeof(object)));
        }
Exemple #13
0
 public static string CheckByRegex(string inputStr, string TypeOfFunction)
 {
     try
     {
         if (TypeOfFunction == "Name")
         {
             RegexStringValidator regName = new RegexStringValidator(@"^[a-zA-Z''-'\s]{1,40}$");
             regName.Validate(inputStr);
         }
         else if (TypeOfFunction == "SSN")
         {
             RegexStringValidator regSSN = new RegexStringValidator(@"^\d{3}-\d{2}-\d{4}$");
             regSSN.Validate(inputStr);
         }
         else if (TypeOfFunction == "Phone")
         {
             RegexStringValidator regPhone = new RegexStringValidator(@"^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$");
             regPhone.Validate(inputStr);
         }
         else if (TypeOfFunction == "Email")
         {
             RegexStringValidator regEmail = new RegexStringValidator(@"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$");
             regEmail.Validate(inputStr);
         }
         else if (TypeOfFunction == "URL")
         {
             RegexStringValidator regURL = new RegexStringValidator(@"^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?$");
             regURL.Validate(inputStr);
         }
         else if (TypeOfFunction == "Password")
         {
             RegexStringValidator regPassword = new RegexStringValidator(@"(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,10})$");
             regPassword.Validate(inputStr);
         }
         else if (TypeOfFunction == "integer") // Non negative Integers
         {
             RegexStringValidator regPInteger = new RegexStringValidator(@"^\d+$");
             regPInteger.Validate(inputStr);
         }
         else if (TypeOfFunction == "Currency") // Non negative Currency
         {
             RegexStringValidator regCurrency = new RegexStringValidator(@"^\d+(\.\d\d)?$");
             regCurrency.Validate(inputStr);
         }
         else if (TypeOfFunction == "CurrencyPN") // Both positive and negative Currency
         {
             RegexStringValidator regCurrencyPN = new RegexStringValidator(@"^(-)?\d+(\.\d\d)?$");
             regCurrencyPN.Validate(inputStr);
         }
         return(inputStr);
     }
     catch (ArgumentException)
     {
         //return e.Message.ToString();
         return("false");
     }
 }
        protected void TextBox1_TextChanged(object sender, EventArgs e) //Check if email is valid.
        {
            RegexStringValidator emailValid = new RegexStringValidator(regexEmail);

            isValidEmail = false;
            try
            {
                emailValid.Validate(EmailTxt.Text);
                isValidEmail = true;
            }
            catch (ArgumentException)
            {
                isValidEmail = false;
            }
            if (isValidEmail == true)
            {
                SqlConnection myConn = GetConnection();
                myConn.Open();
                bool           alreadyHaveAccount = false;
                string         sqlStr             = "select Email from [User];";
                SqlCommand     myCmd = new SqlCommand(sqlStr, myConn);
                SqlDataAdapter da    = new SqlDataAdapter(myCmd);
                DataSet        ds    = new DataSet();
                da.Fill(ds);
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    if (String.Compare(EmailTxt.Text, ds.Tables[0].Rows[i]["Email"].ToString(), 0) == 0)
                    {
                        alreadyHaveAccount = true;
                    }
                }
                if (alreadyHaveAccount == true)
                {
                    EmailTxt.BorderColor = System.Drawing.Color.Red;
                    EmailHint.Text       = "You already have an account!";
                    EmailHint.Visible    = true;
                    EmailTxt.Focus();
                }
                else
                {
                    EmailTxt.BorderColor = System.Drawing.Color.Black;
                    EmailHint.Text       = "";
                    EmailHint.Visible    = false;
                }
                da.Dispose();
                ds.Dispose();
                myConn.Close();
            }
            else
            {
                EmailTxt.BorderColor = System.Drawing.Color.Red;
                EmailHint.Text       = "Please enter a valid email!";
                EmailHint.Visible    = true;
                EmailTxt.Focus();
            }
        }
Exemple #15
0
    private Boolean chkNumber(string val)
    {
        Boolean err = true;
        RegexStringValidator reg = new RegexStringValidator("^[0-9]+$");

        try
        {
            reg.Validate(val);
        }
        catch
        {
            err = false;
        }
        return(err);
    }
Exemple #16
0
    //Validerer et pattern (Regular expression)
    public void ValidatePattern(string ControllerName, dynamic e, FormView FormViewName, string Pattern, string Besked)
    {
        TextBox PatternController             = FormViewName.FindControl(ControllerName) as TextBox;
        string  ControlPattern                = Pattern;
        RegexStringValidator PatternValidator = new RegexStringValidator(ControlPattern);

        try
        {
            PatternValidator.Validate(PatternController.Text);
            (FormViewName.FindControl(ControllerName + "Msg") as Label).Text = "";
        }
        catch (ArgumentException)
        {
            e.Cancel = true;
            (FormViewName.FindControl(ControllerName + "Msg") as Label).Text = Besked;
        }
    }
Exemple #17
0
        protected void Button_Submit_Click(object sender, EventArgs e)
        {
            Utility u1 = new Utility();
            RegexStringValidator rg1 = new RegexStringValidator(u1.GetRegex_email());

            try
            {
                rg1.Validate(TextBox_new.Text);
                u1.UpdateStudentEmail(TextBox_new.Text, Label4.Text);
                Server.Transfer("StartForm.aspx");
            }
            catch (ArgumentException e1)
            {
                string s1 = e1.Message;
                Label3.Text = "Invalid address - please re-type";
            }
        }
Exemple #18
0
        public ActionResult Feedbackrecord(Feedbackrecord feedbackrecord)
        {
            Guid            Memberid  = Guid.Parse(Session["Memberid"].ToString());
            Memberblacklist blacklist = new Memberblacklist();
            string          ipaddress;

            ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (ipaddress == "" || ipaddress == null)
            {
                ipaddress = Request.ServerVariables["REMOTE_ADDR"];
            }
            Members Member = membersService.GetByID(Memberid);
            RegexStringValidator myRegexValidator = new RegexStringValidator(@"/^[0 - 9] *$/");

            if (feedbackrecord.Money > Member.Feedbackmoney || feedbackrecord.Money <= 0 || myRegexValidator.CanValidate(feedbackrecord.Money.GetType()))
            {
                blacklist.Account   = Member.Account;
                blacklist.Memberid  = Guid.Parse(Session["Memberid"].ToString());
                blacklist.Useragent = Request.UserAgent;
                blacklist.IP_Addr   = ipaddress;
                memberblacklistService.Create(blacklist);
                memberblacklistService.SaveChanges();
                Session.RemoveAll();
                return(RedirectToAction("Home", "HomeMs"));
            }
            /*** 金額不得小於500 ***/
            if (feedbackrecord.Money < 500)
            {
                return(RedirectToAction("Feedbackrecord"));
            }
            IEnumerable <Feedbackrecord> old_data = feedbackrecordService.Get().Where(a => a.Memberid == Memberid).OrderByDescending(o => o.Createdate);
            int count = old_data.Count();

            if (count == 0)
            {
                Session["Remains"] = Member.Feedbackmoney;
            }
            else
            {
                Session["Remains"] = old_data.FirstOrDefault().Remains;
            }
            Session["Money"] = feedbackrecord.Money;
            return(RedirectToAction("Feedbacktransfer"));
        }
        public override void Validate()
        {
            base.Validate();

            if (this.IsValid)
            {
                string sku = (string)this.Value;

                // 1. Check to make sure the product sku is not empty
                if (string.IsNullOrEmpty(sku))
                {
                    this.IsValid      = false;
                    this.ErrorMessage = Resources.ProductCanNotBeEmpty;
                    return;
                }
                else
                {
                    // 2. Validate that the product sku is in the right format
                    RegexStringValidator regexStringValidator = new RegexStringValidator(ProductSkuRegEx);
                    try
                    {
                        regexStringValidator.Validate(sku);
                    }
                    catch (ArgumentException)
                    {
                        this.IsValid      = false;
                        this.ErrorMessage = Resources.InvalidProductSkuFormat;
                        return;
                    }

                    // 3. Validate that the product sku exists in the product catalog system
                    IProductCatalogRepository productCatalogRepository =
                        SharePointServiceLocator.Current.GetInstance <IProductCatalogRepository>();

                    if (productCatalogRepository.GetProductBySku(sku) == null)
                    {
                        this.IsValid      = false;
                        this.ErrorMessage = Resources.ProductNotFound;
                        return;
                    }
                }
            }
        }
        private void ValidateRegexTextBox(TextBox validationBox)
        {
            try
            {
                if (validationBox.Text.Length > 0)
                {
                    var validator = new RegexStringValidator(validationBox.Text);
                }

                _errorProvider.SetError(validationBox, "");
                validationBox.ForeColor = Color.Black;
            }
            catch (ArgumentException e)
            {
                _errorProvider.SetIconAlignment(validationBox, ErrorIconAlignment.MiddleRight);
                _errorProvider.SetIconPadding(validationBox, -20);
                _errorProvider.SetError(validationBox, "The regular expression is incorrect:" + "\n" + e.Message);
                validationBox.ForeColor = Color.Red;
            }
        }
        /*
         *   METHOD        : CheckFlagFormat
         *   DESCRIPTION   : Checks the format of the principle string, and filters the dollar value if required
         *   PARAMETERS    : void : Has no parameters
         *   RETURNS       : bool : True if no errors detected
         */
        private bool CheckFlagFormat()
        {
            bool flagValid  = false;
            var  flagString = a03_ParamPanel.Controls["flagTxtBox"].Text;

            try
            {
                //Throw exception if they input any character except a single flag value of 1 or 2
                RegexStringValidator stringValidator = new RegexStringValidator(@"^[1-2]$");
                stringValidator.Validate(flagString);

                flagValid = true;
            }
            catch (Exception argEx)
            {
                //DEBUG SET THE LABEL TO THE RIGHT OF THE TXT BOX TO INDICATE ERROR
                Logger.RecordError(argEx.Message);
            }
            return(flagValid);
        }
Exemple #22
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);
        }
Exemple #23
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);
        }
Exemple #24
0
        public OptionObject2015 Execute()
        {
            string[] temp = _parameter.Split(',');
            var      returnOptionObject = new OptionObject2015();
            var      formObject         = new FormObject();
            var      verifyDataField    = new FieldObject();
            string   holdValidChars     = temp[3];
            string   fieldDesc          = temp[4];
            string   holdValidsAddr     = "^[a-zA-Z0-9 ]*$";
            string   holdValidsName     = "^[a-zA-Z0-9, ]*$";
            string   holdValids;

            //RegexStringValidator re = new RegexStringValidator(holdValidChars);
            if (holdValidChars == "N")
            // valid characters for a name field
            {
                holdValids = holdValidsName;
            }
            else
            // valid characters for an address field
            {
                holdValids = holdValidsAddr;
            }

            RegexStringValidator re = new RegexStringValidator(holdValids);

            string returnMessage = "";

            try
            {
                formObject.FormId           = temp[1];
                verifyDataField.FieldNumber = temp[2];

                foreach (var form in _optionObject2015.Forms)
                {
                    foreach (var field in form.CurrentRow.Fields)
                    {
                        if (field.FieldNumber == verifyDataField.FieldNumber)
                        {
                            verifyDataField.FieldValue   = field.FieldValue;
                            formObject.MultipleIteration = form.MultipleIteration;
                        }
                    }
                }
                // allow regular characters

                re.Validate(verifyDataField.FieldValue);
                //var fields = new FieldObject[1];
                //fields[0] = verifyDataField;
                var currentRow = new RowObject
                {
                    Fields = new List <FieldObject>
                    {
                        verifyDataField
                    }
                };
                foreach (var form in _optionObject2015.Forms)
                {
                    if (form.FormId == formObject.FormId)
                    {
                        currentRow.RowId       = form.CurrentRow.RowId;
                        currentRow.ParentRowId = form.CurrentRow.ParentRowId;
                    }
                }
            }
            catch (ArgumentException eo)
            {
                returnMessage = "There are one or more special characters in the '"
                                + fieldDesc + "' field";
                returnOptionObject.ErrorCode = 1;
                logger.Error(eo, returnMessage);
            }

            catch (Exception e)
            {
                returnMessage = e.Message + " -Validate Character Field- \n\n" +
                                e.GetType().ToString() + "\n" +
                                e.StackTrace;
                returnOptionObject.ErrorCode = 3;
                logger.Error(e, "An error occurred. Error: {errorMessage}.", e.Message);
            }

            returnOptionObject.ErrorMesg = returnMessage;

            returnOptionObject.EntityID        = _optionObject2015.EntityID;
            returnOptionObject.EpisodeNumber   = _optionObject2015.EpisodeNumber;
            returnOptionObject.Facility        = _optionObject2015.Facility;
            returnOptionObject.NamespaceName   = _optionObject2015.NamespaceName;
            returnOptionObject.OptionId        = _optionObject2015.OptionId;
            returnOptionObject.OptionStaffId   = _optionObject2015.OptionStaffId;
            returnOptionObject.OptionUserId    = _optionObject2015.OptionUserId;
            returnOptionObject.ParentNamespace = _optionObject2015.ParentNamespace;
            returnOptionObject.ServerName      = _optionObject2015.ServerName;
            returnOptionObject.SystemCode      = _optionObject2015.SystemCode;
            returnOptionObject.SessionToken    = _optionObject2015.SessionToken;

            return(returnOptionObject);
        }
Exemple #25
0
        public void Match_fail()
        {
            RegexStringValidator v = new RegexStringValidator("[a-z]+");

            AssertExtensions.Throws <ArgumentException>(null, () => v.Validate("1234"));
        }
Exemple #26
0
        static void Main(string[] args)
        {
            var lengthValidator          = new StringLengthValidator(18);
            var regexValidator           = new RegexStringValidator("^[A-Z ]+$");
            var rangeRaceMarginValidator = new RangeDecimalValidator(110, 140);
            var numOfRunnersValidator    = new RangeIntValidator(4, 16);

            int            capacity;
            ValidateResult rangeResult;

            do
            {
                Console.WriteLine("How many runners do you want for the race [4-16]:");
                var numOfRunners = Console.ReadLine();
                int.TryParse(numOfRunners, out capacity);
                rangeResult = numOfRunnersValidator.Validate(capacity);
                if (!rangeResult.Succeeded)
                {
                    Console.WriteLine(string.Concat(rangeResult.Errors.Select(e => e)));
                    Console.WriteLine();
                }
            } while (capacity == 0 || !rangeResult.Succeeded);

            var runners = new IRunner[capacity];

            Console.WriteLine();
            for (int i = 0; i < capacity; i++)
            {
                var            currentRunnerId = i + 1;
                ValidateResult lengthResult;
                ValidateResult regexResult;
                var            runnerName = string.Empty;
                do
                {
                    Console.WriteLine($"Please give me the name of runner{currentRunnerId}:");
                    runnerName   = Console.ReadLine();
                    lengthResult = lengthValidator.Validate(runnerName);
                    regexResult  = regexValidator.Validate(runnerName);
                    if (!lengthResult.Succeeded)
                    {
                        Console.WriteLine(string.Concat(lengthResult.Errors.Select(e => e)));
                    }
                    if (!regexResult.Succeeded)
                    {
                        Console.WriteLine(string.Concat(regexResult.Errors.Select(e => e)));
                    }
                    Console.WriteLine();
                } while (!lengthResult.Succeeded || !regexResult.Succeeded);

                var fractionIsValid = true;
                do
                {
                    Console.WriteLine($"Please give me the fractional odd for runner{currentRunnerId}:");
                    var fractionalOdd = Console.ReadLine();
                    try
                    {
                        var fraction = new Fraction(fractionalOdd);
                        var runner   = new Runner(runnerName, fraction);
                        runners[i]      = runner;
                        fractionIsValid = true;
                    }
                    catch (InvalidFractionException ex)
                    {
                        fractionIsValid = false;
                        Console.WriteLine(ex.Message);
                        Console.WriteLine();
                    }
                } while (fractionIsValid == false);
                Console.WriteLine();
            }

            var   calculator = new RaceMarginCalculator();
            IRace race       = new Race(runners, calculator);
            var   raceMargin = race.CalculateRaceMargin();

            Console.WriteLine(raceMargin);
            ValidateResult raceMarginResult = rangeRaceMarginValidator.Validate(raceMargin);

            if (!raceMarginResult.Succeeded)
            {
                Console.WriteLine(string.Concat(raceMarginResult.Errors.Select(e => e)));
            }

            Console.WriteLine();
            race.CalculateRunnersWinningPercentage();

            var appearances = new List <RunnerAppearance>();

            foreach (var runner in runners)
            {
                appearances.Add(new RunnerAppearance(runner.Name, runner.WinningPercentage, 0));
            }

            string menuOption;

            do
            {
                Console.WriteLine();
                Console.WriteLine("============Menu==============");
                Console.WriteLine();
                Console.WriteLine("Choose P to pick a winner (P)");
                Console.WriteLine("Choose A to display the number of appearances for each runner based on winning percentage (A)");
                Console.WriteLine("Choose W to display the winning percentage for each runner (A)");
                Console.WriteLine("Choose Q to exit (Q)");
                Console.WriteLine();
                Console.WriteLine("Select an option:");
                menuOption = Console.ReadLine();
                var rnd = new Random();

                switch (menuOption)
                {
                case "P":
                    Console.WriteLine();
                    Console.WriteLine("Please select how many iterations do you want ?");
                    Console.WriteLine();
                    Console.WriteLine("Select 1 for 1 iteration (1):");
                    Console.WriteLine("Select 10 for 10 iterations (10):");
                    Console.WriteLine("Select 100 for 100 iterations (100):");
                    Console.WriteLine("Select 1,000 for 1,000 iterations (1,000):");
                    Console.WriteLine("Select 10,000 for 10,000 iterations (10,000):");
                    Console.WriteLine("Select 100,000 for 100,000 iterations (100,000):");
                    Console.WriteLine("Select 1,000,000 for 1,000,000 iterations (1,000,000):");
                    menuOption = Console.ReadLine();
                    int.TryParse(menuOption, out int iterations);
                    switch (menuOption)
                    {
                    case "1":
                    case "10":
                    case "100":
                    case "1000":
                    case "10000":
                    case "100000":
                    case "1000000":
                        for (int i = 0; i < iterations; i++)
                        {
                            var randomNum = rnd.Next(1, 101);
                            PickWinner(randomNum, race, appearances);
                        }
                        break;

                    default:
                        break;
                    }
                    break;

                case "A":
                    DisplayRunnerAppearances(appearances);
                    break;

                case "W":
                    DisplayWinningPercentages(runners);
                    break;

                case "Q":
                    break;
                }
            } while (menuOption != null && !menuOption.Equals("Q"));
            Environment.Exit(0);

            Console.ReadKey();
        }
Exemple #27
0
    public static string normalCheck(string weekRegC, int startNC, int endNC, int dayWC, string ClassNC, string TeacherNC)
    {
        string msg = "OK";

        if (weekRegC == string.Empty)
        {
            msg = "周输入不可为空";
            return(msg);
        }

        RegexStringValidator regday = new RegexStringValidator("^[1-7]{1}$");
        //RegexStringValidator regnum = new RegexStringValidator("^[1-9]{1}$|^1[10]{1}");//1-11
        RegexStringValidator regnum = new RegexStringValidator("^[1-9]{1}$|10|99");

        try
        {
            regday.Validate(dayWC.ToString());
        }
        catch
        {
            msg = "日期只能填数字1至数字7";
            return(msg);
        }
        try
        {
            regnum.Validate(startNC.ToString());
            regnum.Validate(endNC.ToString());
        }
        catch
        {
            msg = "节次只能填数字1至数字10和99(中午)";
            return(msg);
        }

        if ((startNC != 99) && (endNC != 99))
        {
            if (startNC > endNC)
            {
                msg = "开始节次不能大于结束节次";
                return(msg);
            }
        }
        if ((startNC == 99) || (endNC == 99))
        {
            if (startNC != endNC)
            {
                msg = "节次如果是中午,则开始和结束都必须是中午";
                return(msg);
            }
        }


        if (ClassNC == string.Empty)
        {
            msg = "班级名未填写";
            return(msg);
        }
        if (TeacherNC == string.Empty)
        {
            msg = "教师名未填写";
            return(msg);
        }
        return(msg);
    }
        void emailButton_Click(object sender, EventArgs e)
        {
            String emailAddress = emailBox.Text.Trim();

            if (emailAddress == String.Empty)
            {
                return;
            }


            RegexStringValidator regex = new RegexStringValidator(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");

            try {
                regex.Validate(emailAddress);
            } catch {
                ErrorMessage = "E-mail address is not valid";
                return;
            }


            String createDateStr = String.Empty;

            createDateStr = createDateList.SelectedValue;

            DollarSaverDB.CertificateNumberDataTable certificateNumbers;
            if (createDateStr == String.Empty)
            {
                certificateNumbers = certificate.AllNumbers;
                createDateStr      = "All Dates";
            }
            else
            {
                DateTime createDate = DateTime.Now;
                try {
                    createDate    = Convert.ToDateTime(createDateStr);
                    createDateStr = createDate.ToString("MM/dd/yyyy");
                } catch {
                    ErrorMessage = "Create Date must by in the format MM/DD/YYYY";
                    return;
                }

                CertificateNumberTableAdapter certificateNumberAdapter = new CertificateNumberTableAdapter();
                certificateNumbers = certificateNumberAdapter.GetByCertificateAndCreateDate(certificateId, createDate);
            }

            //MailMessage message = new MailMessage("*****@*****.**", "*****@*****.**");
            MailMessage message = new MailMessage("\"DollarSaver\" <*****@*****.**>", emailAddress);


            message.IsBodyHtml = true;


            message.Subject = "Certificate Numbers For " + certificate.AdvertiserName;

            String body = "<html><body><span style=\"font-family: Verdana; font-size: 12pt;\">";

/*
 *          body += "<table cellpadding=\"3\" cellspacing=\"0\" border=\"0\" width=\"550px\">" + Environment.NewLine +
 *              "<tr><td align=\"center\" style=\"font-size: 18pt;\">Advertiser: " + certificate.Advertiser.Name + "</td></tr>" + Environment.NewLine +
 *              "<tr><td align=\"center\"><HR width=\"100%\" ></td></tr>" + Environment.NewLine +
 *              "<tr><td align=\"left\">Station: " + Station.Name + "</td></tr>" + Environment.NewLine +
 *              "<tr><td align=\"left\">Certificate: " + certificate.ShortName + "</td></tr>" + Environment.NewLine +
 *              "<tr><td align=\"left\">Create Date: " + createDateStr + "</td></tr>" + Environment.NewLine +
 *              "<tr><td align=\"left\">Quantity: " + certificateNumbers.Count + "</td></tr>" + Environment.NewLine +
 *              "<tr><td align=\"center\"><HR width=\"100%\" ></td></tr>" + Environment.NewLine +
 *              "<tr><td align=\"center\" style=\"font-size: 18pt;\"><U>CERTIFICATE NUMBERS</U></td></tr>" + Environment.NewLine +
 *              "<tr><td align=\"center\"><B>Cross out number when certificate is redeemed</B></td></tr>" + Environment.NewLine +
 *              "<tr><td align=\"center\"><B>--&gt; Read numbers Left to Right --&gt;</B></td></tr>" +
 *              "<tr><td align=\"center\"><HR width=\"100%\" ></td></tr>" + Environment.NewLine;
 */
            body += "<table cellpadding=\"3\" cellspacing=\"0\" border=\"0\" width=\"550px\">" + Environment.NewLine +
                    "<tr><td align=\"center\" style=\"font-size: 14pt;\">" + certificateNumbers.Count + " Certificate Numbers for " + certificate.Advertiser.Name + "</td></tr>" + Environment.NewLine +
                    "<tr><td align=\"center\" style=\"font-size: 10pt;\">Certificate: " + certificate.ShortName + "</td></tr>" + Environment.NewLine +
                    "<tr><td align=\"center\" style=\"font-size: 8pt;\"><B>Cross out number when certificate is redeemed</B> --&gt; Read numbers Left to Right --&gt;</B></td></tr>" +
                    "<tr><td align=\"center\"><HR width=\"100%\" ></td></tr>" + Environment.NewLine;

            body += "<tr><td><table cellpadding=\"3\" cellspacing=\"0\" border=\"0\" width=\"100%\">";
            for (int i = 0; i < certificateNumbers.Count; i += 3)
            {
                body += "<tr><td style=\"font-size: 20pt\" align=\"center\">" + certificateNumbers[i].Number + "</td>" + Environment.NewLine;

                if (i + 1 < certificateNumbers.Count)
                {
                    body += "<td style=\"font-size: 20pt\" align=\"center\">" + certificateNumbers[i + 1].Number + "</td>" + Environment.NewLine;
                }
                else
                {
                    body += "<td style=\"font-size: 20pt\" align=\"center\">&nbsp;</td>" + Environment.NewLine;
                }
                if (i + 2 < certificateNumbers.Count)
                {
                    body += "<td style=\"font-size: 20pt\" align=\"center\">" + certificateNumbers[i + 2].Number + "</td></tr>" + Environment.NewLine;
                }
                else
                {
                    body += "<td style=\"font-size: 20pt\" align=\"center\">&nbsp;</td></tr>" + Environment.NewLine;
                }
            }
            body += "</table></tr></td>";

            body += "<tr><td align=\"center\"><HR width=\"100%\" ></td></tr></table></body></html>";

            // end message with a <CRLF>.<CRLF> ??

            message.Body = body;

            bool success = false;

            try {
                //SmtpClient smtp = new SmtpClient("localhost", 25);
                //smtp.Send(message);

                Mailer mailer = new Mailer();
                mailer.Send(message);

                InfoMessage = "Certificate Numbers sent to: " + emailAddress;
                success     = true;
            } catch (Exception ex) {
                ErrorMessage = "Error Sending E-mail: " + ex.Message;
            }

            if (success)
            {
                Response.Redirect("~/admin/CertificateEdit.aspx?id=" + certificateId);
            }
        }
Exemple #29
0
    //“周”正则转换为存储过程可用的逗号分隔数据
    public static bool regToData(string strReg, out string strData)
    {
        int maxWeek = getCurMaxWeek();
        //两位数字+横杆(-)+两位数字 或 数字 + 逗号/横杠(总字符数1至50 + 4)(逗号/横杠不可在开头,不可在结尾,可以为纯数字)
        RegexStringValidator regweek   = new RegexStringValidator("^[1-9]{0,1}[0-9]{1,1}[-][1-9]{0,1}[0-9]{1,1}$|^[1-9]{0,1}[0-9]{1,1}[0-9,-]{0,50}[1-9]{0,1}[0-9]{0,1}$");
        RegexStringValidator regweekMN = new RegexStringValidator("^[1-9]{0,1}[0-9]{1,1}[-][1-9]{0,1}[0-9]{1,1}$");
        string strWeekRegToData        = "";

        try
        {
            regweek.Validate(strReg);
        }
        catch (Exception)
        {
            strData = "存在非法字符或格式不正确,输入示例:1-3或1,3,5,6,8或1";
            return(false);
        }
        if (strReg.Contains("-"))
        {
            if (strReg.Contains(","))                      //reg含有逗号,横杆,数字
            {
                string[]      weekD   = strReg.Split(','); //按逗号切割reg
                List <string> weekOut = new List <string>();
                for (int i = 0; i < weekD.Count(); i++)
                {
                    string weekDataI = weekD[i];
                    if (weekDataI == "")
                    {
                        strData = "逗号前后必须都有数字";
                        return(false);
                    }
                    if (weekDataI.Contains("-"))
                    {
                        try
                        {
                            regweekMN.Validate(weekDataI);
                        }
                        catch (Exception)
                        {
                            strData = "按逗号切割后存在非法字符,输入示例:1-3或1,3,5,6,8或1,数字不可大于当前学期最大周";
                            return(false);
                        }
                        //切割后数据为m-n
                        string[] weekMN = weekDataI.Split('-');
                        int      firstW = Convert.ToInt16(weekMN[0]);
                        int      lastW  = Convert.ToInt16(weekMN[1]);
                        //周数不可为0
                        if ((firstW == 0) | (lastW == 0))
                        {
                            strData = "切割后周数不可为0";
                            return(false);
                        }
                        //开始周不可大于结束周
                        if (firstW > lastW)
                        {
                            strData = "切割后开始周不可大于结束周";
                            return(false);
                        }
                        //结束周不可大于当前学期最大周数
                        if (lastW > maxWeek)
                        {
                            strData = "切割后结束周不可大于当前学期最大周数";
                            return(false);
                        }
                        //m-n转换为m,m+1,...,n-1,n
                        for (int j = firstW; j <= lastW; j++)
                        {
                            //strWeekRegToData = strWeekRegToData + j + ",";
                            weekOut.Add(j + ",");
                        }
                    }
                    else
                    {
                        //切割后数据为m
                        if (Convert.ToInt16(weekDataI) == 0)
                        {
                            strData = "周数不可为0";
                            return(false);
                        }
                        if (Convert.ToInt16(weekDataI) > maxWeek)
                        {
                            strData = "周不可大于当前学期最大周数";
                            return(false);
                        }
                        //strWeekRegToData = strWeekRegToData + weekDataI + ",";
                        weekOut.Add(weekDataI + ",");
                    }
                }
                if (weekOut.Distinct().Count() != weekOut.Count())
                {
                    strData = "切割后周有重复";
                    return(false);
                }
                //weekOut.Sort();
                weekOut = weekOut.OrderBy(s => int.Parse(Regex.Match(s, @"\d+").Value)).ToList();
                for (int i = 0; i < weekOut.Count; i++)
                {
                    strWeekRegToData = strWeekRegToData + weekOut[i];
                }
                if (strWeekRegToData != "")
                {
                    strWeekRegToData = strWeekRegToData.Substring(0, strWeekRegToData.Length - 1);
                    strData          = strWeekRegToData;
                    return(true);
                }
                else
                {
                    strData = "切割后reg转data失败,只有“-”和数字";
                    return(false);
                }
            }
            else
            {
                //weekReg字段只有“-”和数字
                try
                {
                    regweekMN.Validate(strReg);
                }
                catch (Exception)
                {
                    strData = "存在非法字符,数字不可大于当前学期最大周,只有“-”和数字";
                    return(false);
                }

                string[] weekD = strReg.Split('-');

                //横杠两端必须有数字
                if ((weekD[0] == "") || (weekD[1] == ""))
                {
                    strData = "横杠两端必须有数字";
                    return(false);
                }

                int firstWeek = Convert.ToInt16(weekD[0]);
                int lastWeek  = Convert.ToInt16(weekD[1]);
                //横杠数只能为1
                if (weekD.Count() != 2)
                {
                    strData = "横杠数只能为1";
                    return(false);
                }
                //周数不可为0
                if ((firstWeek == 0) | (lastWeek == 0))
                {
                    strData = "周数不可为0";
                    return(false);
                }
                //开始周不可大于结束周
                if (firstWeek > lastWeek)
                {
                    strData = "开始周不可大于结束周";
                    return(false);
                }
                //结束周不可大于当前学期最大周数
                if (lastWeek > maxWeek)
                {
                    strData = "结束周不可大于当前学期最大周数";
                    return(false);
                }
                //m-n转换为m,m+1,...,n-1,n
                for (int i = firstWeek; i <= lastWeek; i++)
                {
                    strWeekRegToData = strWeekRegToData + i + ",";
                }
                if (strWeekRegToData != "")
                {
                    strWeekRegToData = strWeekRegToData.Substring(0, strWeekRegToData.Length - 1);
                    strData          = strWeekRegToData;
                    return(true);
                }
                else
                {
                    strData = "reg转data失败,只有“-”和数字";
                    return(false);
                }
            }
        }
        else if (strReg.Contains(","))//reg含逗号和数字,逗号不在开头结尾
        {
            string[] weekD = strReg.Split(',');
            for (int i = 0; i < weekD.Count(); i++)
            {
                if (weekD[i] == "")
                {
                    strData = "逗号前后必须都有数字";
                    return(false);
                }
                if (Convert.ToInt16(weekD[i]) == 0)
                {
                    strData = "周数不可为0";
                    return(false);
                }
                if (Convert.ToInt16(weekD[i]) > maxWeek)
                {
                    strData = "周不可大于当前学期最大周数";
                    return(false);
                }
                if (weekD.Distinct().Count() != weekD.Length)
                {
                    strData = "周有重复";
                    return(false);
                }


                strWeekRegToData = strWeekRegToData + weekD[i] + ",";
            }
            if (strWeekRegToData != "")
            {
                strWeekRegToData = strWeekRegToData.Substring(0, strWeekRegToData.Length - 1);
                strData          = strWeekRegToData;
                return(true);
            }
            else
            {
                strData = "reg转data失败,逗号和数字";
                return(false);
            }
        }
        else //reg只有数字
        {
            if (Convert.ToInt16(strReg) == 0)
            {
                strData = "周数不可为0";
                return(false);
            }
            if (Convert.ToInt16(strReg) > maxWeek)
            {
                strData = "周不可大于当前学期最大周数";
                return(false);
            }
        }



        strData = strReg;
        return(true);
    }
 private Boolean chkNumber(string val)
 {
     Boolean err = true;
     RegexStringValidator reg = new RegexStringValidator("^[0-9]+$");
     try
     {
         reg.Validate(val);
     }
     catch
     {
         err = false;
     }
     return err;
 }
Exemple #31
0
        private void checkEmail_Click(object sender, EventArgs e)
        {
            con = new SqlConnection(connectionString);
            con.Open();
            SqlCommand checkEmail = new SqlCommand();

            checkEmail.CommandText = "select * from [Customer]";
            checkEmail.Connection  = con;

            SqlDataReader rd = checkEmail.ExecuteReader();

            string pattern = @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"; //check for invalid inputs
            RegexStringValidator myRegexValidator = new RegexStringValidator(pattern);

            try
            {
                myRegexValidator.Validate(emailBox.Text); //checking what has been typed and if it matches the pattern.
            }
            catch (Exception)
            {
                MessageBox.Show("Invalid Email");
            }

            while (rd.Read())
            {
                if (rd[4].ToString() == emailBox.Text) //the 4 here is calling to the Email col
                {                                      //here we are saying that if rd var is == to the value user input is a match then isreg before true.
                    isreg = true;
                    //we then print it out to the label.
                }
                if (isreg == true)
                {
                    if (rd[3].ToString() == "1")
                    {
                        memcheck.Text = "Member: £20";
                        memtype       = 2;
                    }
                    else if (rd[3].ToString() == "2")
                    {
                        memcheck.Text = "Prm Member: £15";
                        memtype       = 1;
                    }
                    else
                    {
                        memcheck.Text = "Non-Member: £25";
                        memtype       = 3;
                    }
                }
                //code to ask for the correct price from the user so no mistakes are made
            }
            if (isreg == true)
            {
                emailLabel.Text = "Is registerd";
            }
            else
            {
                emailLabel.Text = "Could not find";
            }
            isreg = false;
            con.Close();
            con = new SqlConnection(connectionString);
            SqlDataAdapter checkup = new SqlDataAdapter("SELECT * FROM [Customer] WHERE emailAddress ='" + emailBox.Text + "'", con); //this will get all the data where email matches
            DataTable      sd      = new DataTable();

            checkup.Fill(sd);
            dataGridView2.DataSource = sd;
            con.Close();
        }
Exemple #32
0
 private bool EmailDetecton(string str)
 {
     string pattern = @"^[0-9a-zA-Z\.\-_]+@([a-zA-Z\.\-_]+\.)+[a-zA-Z]{2,4}$";
     RegexStringValidator rsv = new RegexStringValidator(pattern);
     try
     {
         rsv.Validate(str);
         return true;
     }
     catch
     {
         return false;
     }
 }