public static void AddRegularExpressionValidator(DetailsView view, int rowIndex, RegexPattern type) { string msg = "", patter = ""; if (type == RegexPattern.Number) { patter = NUMBER; msg = NUMBER_MSG; } else if (type == RegexPattern.Date) { patter = DATE; msg = DATE_MSG; } else if (type == RegexPattern.Mobile) { patter = MOBILE; msg = MOBILE_MSG; } DetailsViewRow row = view.Rows[rowIndex]; DataControlFieldCell cell = row.Cells[1] as DataControlFieldCell; string ctlID = cell.Controls[0].UniqueID; string clientID = cell.Controls[0].ClientID; int pos = clientID.LastIndexOf("_"); if (pos > 0) { RegularExpressionValidator Reg = new RegularExpressionValidator(); Reg.Text = String.Format("<p style='margin:0;'>{0}</p>", msg); Reg.Display = System.Web.UI.WebControls.ValidatorDisplay.Dynamic; Reg.ControlToValidate = ctlID.Substring((pos + 1)); Reg.ValidationExpression = patter; cell.Controls.Add(Reg); } }
public void CaseSensitiveStringMatching() { RegularExpressionValidator validator = new RegularExpressionValidator("ToString()", "true", @"[A-Z][a-z]*"); Assert.IsTrue(validator.Validate("Aleksandar", new ValidationErrors())); Assert.IsFalse(validator.Validate("ALEKSANDAR", new ValidationErrors())); Assert.IsFalse(validator.Validate("aleksandar", new ValidationErrors())); }
public void When_the_text_is_empty_then_the_validator_should_fail() { string input = ""; var validator = new RegularExpressionValidator(@"^\w\d$"); var result = validator.Validate(new PropertyValidatorContext(null, new object(), x => input)); result.IsValid().ShouldBeFalse(); }
public void When_the_text_matches_the_regular_expression_then_the_validator_should_pass() { string input = "S3"; var validator = new RegularExpressionValidator(@"^\w\d$"); var result = validator.Validate(new PropertyValidatorContext(null, new object(), x => input)); result.IsValid().ShouldBeTrue(); }
public void Init() { Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-us"); validator = new RegularExpressionValidator("abc"); validator.Initialize(new CachedValidationRegistry(), typeof(TestTarget).GetProperty("TargetField")); target = new TestTarget(); }
/// <summary> /// 创建浮点型校验控件 /// </summary> /// <param name="fForm">表单对象</param> /// <param name="fControl">绑定的控件 </param> public static void CreateDoubleValidator(HtmlForm fForm, Control fControl) { RegularExpressionValidator validator = new RegularExpressionValidator(); validator.ValidationExpression = "^[0-9]+(.[0-9]{1,16})?$"; validator.ErrorMessage = "格式必须为数值"; validator.ControlToValidate = fControl.ID; //validator.EnableViewState = false; fForm.Controls.AddAt(fForm.Controls.IndexOf(fControl) + 1, validator); }
public static void AddTypeValidators(Table t, DataTable dt) { int numRows = t.Rows.Count; for (int i = 0; i < numRows; i++) { string dataType = (string)dt.Rows[i+1].ItemArray[1]; switch (dataType) { case "float": { RegularExpressionValidator rev = new RegularExpressionValidator(); rev.ValidationExpression = "^[+-]?[\\d,]*(\\.\\d*)?$"; rev.ErrorMessage = "This field requires a valid number."; TextBox tb = (TextBox)t.Rows[i].Cells[1].Controls[0]; rev.ControlToValidate = tb.ID; t.Rows[i].Cells[3].Controls.Add(rev); break; } case "int": { RegularExpressionValidator rev = new RegularExpressionValidator(); rev.ValidationExpression = "^\\d+$"; rev.ErrorMessage = "This field is limited to integers."; TextBox tb = (TextBox)t.Rows[i].Cells[1].Controls[0]; rev.ControlToValidate = tb.ID; t.Rows[i].Cells[3].Controls.Add(rev); break; } case "money": { RegularExpressionValidator rev = new RegularExpressionValidator(); rev.ValidationExpression = "^\\$?[+-]?[\\d,]*(\\.\\d*)?$"; rev.ErrorMessage = "This field requires a valid currency value."; TextBox tb = (TextBox)t.Rows[i].Cells[1].Controls[0]; rev.ControlToValidate = tb.ID; t.Rows[i].Cells[3].Controls.Add(rev); break; } case "datetime": { RegularExpressionValidator rev = new RegularExpressionValidator(); rev.ValidationExpression = "^((0?[13578]|10|12)(-|\\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[01]?))(-|\\/)((19)([2-9])(\\d{1})|(20)([01])(\\d{1})|([8901])(\\d{1}))|(0?[2469]|11)(-|\\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[0]?))(-|\\/)((19)([2-9])(\\d{1})|(20)([01])(\\d{1})|([8901])(\\d{1})))$"; rev.ErrorMessage = "This field requires a date in the MM/DD/YYYY format."; TextBox tb = (TextBox)t.Rows[i].Cells[1].Controls[0]; rev.ControlToValidate = tb.ID; t.Rows[i].Cells[3].Controls.Add(rev); break; } case "varchar": { break; } } } }
void RegularExpression(TextBox tb) { RegularExpressionValidator rEV = new RegularExpressionValidator(); rEV.ControlToValidate = tb.ID; rEV.ValidationExpression = "[.\\-_a-z0-9]+@([a-z0-9][\\-a-z0-9]+\\.)+[a-z]{2,6}"; rEV.ErrorMessage = "E-Mail provided is invalid!"; rEV.Text = "E-Mail provided is invalid!"; rEV.ForeColor = Color.Red; form1.Controls.Add(rEV); }
/// <summary> /// When the FileUpload control is validated at the client, /// the FileName property being validated includes the complete path: C:\Images\MyFile.jpg. /// When it gets to the server, the FileUpload control's FileName property is MyFile.jpg. /// The path is removed.That's why the regular expression is failing. /// you can solve by use this ValidationExpression /// .*(\.[Jj][Pp][Gg]|\.[Gg][Ii][Ff]|\.[Jj][Pp][Ee][Gg]|\.[Pp][Nn][Gg])$ /// or use this Method to solve any ValidationExpression when back to server /// </summary> public static void ClientScriptValidator(Page PageAspx, RegularExpressionValidator Regular) { if (PageAspx != null && Regular != null) { string stordRegular = Regular.ValidationExpression; Regular.Enabled = false; PageAspx.Validate(); Regular.Enabled = true; Regular.ValidationExpression = stordRegular; } }
//Fill page with dynamic controls showing products in database private void GenerateControls() { //Get all productObjects from database ArrayList productList = ConnectionClass.GetProductByType("%"); foreach (Product product in productList) { //Create Controls Panel productPanel = new Panel(); Image image = new Image { ImageUrl = product.Image, CssClass = "ProductsImage" }; Literal literal = new Literal { Text = "<br />" }; Literal literal2 = new Literal { Text = "<br />" }; Label lblName = new Label { Text = product.Name, CssClass = "ProductsName" }; Label lblPrice = new Label { Text = String.Format("$ {0:0.00}", product.Price + "<br />"), CssClass = "ProductsPrice" }; TextBox textBox = new TextBox { ID = product.Id.ToString(), CssClass = "ProductsTextBox", Width = 60, Text = "0" }; //Add validation so only numbers can be entered into the textfields RegularExpressionValidator regex = new RegularExpressionValidator { ValidationExpression = "^[0-9]*", ControlToValidate = textBox.ID, ErrorMessage = "Please enter a number." }; //Add controls to Panels productPanel.Controls.Add(image); productPanel.Controls.Add(literal); productPanel.Controls.Add(lblName); productPanel.Controls.Add(literal2); productPanel.Controls.Add(lblPrice); productPanel.Controls.Add(textBox); productPanel.Controls.Add(regex); pnlProducts.Controls.Add(productPanel); } }
public BaseValidator getPatternValidator(string pattern, string controlID) { RegularExpressionValidator rev = new RegularExpressionValidator(); rev.ControlToValidate = controlID; rev.ValidationExpression = pattern; rev.Display = ValidatorDisplay.Dynamic; rev.ErrorMessage = "This field must be match following RegularExpression:\n " + pattern; rev.ValidationGroup = "1"; return(rev); }
private BaseValidator getMinLengthValidator(int minLen, string controlID) { RegularExpressionValidator regexpr = new RegularExpressionValidator(); regexpr.ControlToValidate = controlID; regexpr.ValidationExpression = ".{" + minLen + ",}"; regexpr.ErrorMessage = "String shorter than " + minLen; regexpr.Display = ValidatorDisplay.Dynamic; regexpr.ValidationGroup = "1"; return(regexpr); }
private RegularExpressionValidator GenerateIntREV(Control control) { RegularExpressionValidator rev = new RegularExpressionValidator(); rev.ControlToValidate = control.ID; rev.Display = ValidatorDisplay.Dynamic; rev.ValidationExpression = @"-?[1-9]+\d*"; rev.Text = "* Integer is in the wrong format"; return(rev); }
public BaseValidator getPatternValidator(string pattern, string controlID) { RegularExpressionValidator rev = new RegularExpressionValidator(); rev.ControlToValidate = controlID; rev.Display = ValidatorDisplay.Dynamic; rev.ValidationExpression = pattern; rev.ValidationGroup = "1"; rev.ErrorMessage = "This field must be a valid FiscalCode (e.g. FLDPJC09H29G702R)"; return(rev); }
private RegularExpressionValidator GenerateDecimalREV(Control control) { RegularExpressionValidator rev = new RegularExpressionValidator(); rev.ControlToValidate = control.ID; rev.Display = ValidatorDisplay.Dynamic; rev.ValidationExpression = @"-?\d*(.?\d+)?"; rev.Text = "* Decimal is in the wrong format"; return(rev); }
static public void WriteRegularExpressionValidator(HtmlTextWriter writer, RegularExpressionValidator rev, string className, string controlToValidate, string msg, string expression) { if (rev != null) { rev.CssClass = className; rev.ControlToValidate = controlToValidate; rev.ErrorMessage = msg; rev.ValidationExpression = expression; rev.RenderControl(writer); } }
internal static void SendBugReport(ReportBug form) { if (!RegularExpressionValidator.ValidateSingleString(form.emailTextBox.Text, RegularExpressionValidator.RegularExpression.Email)) { WindowManager.ShowAlertBox(form, LanguageUtil.GetCurrentLanguageString("EmailInvalid", className)); return; } String mailString = PrepareMailBugReport(form.sendMeACopyCheckBox.Checked, form.emailTextBox.Text, form.nameTextBox.Text, form.areaComboBox.SelectedItem.ToString(), form.errorMessageTextBox.Text, form.descriptionTextBox.Text); OtherManager.StartProcess(form, mailString); }
/// <summary> /// Add a Regular Expression Validator /// </summary> /// <param name="id"></param> /// <param name="regex"></param> /// <param name="message"></param> /// <param name="parent"></param> internal static RegularExpressionValidator AddRegexValid(string id, string regex, string message, Control parent) { RegularExpressionValidator v = new RegularExpressionValidator(); v.ControlToValidate = id; v.ValidationExpression = regex; v.Text = message; v.Display = ValidatorDisplay.Dynamic; v.Style["margin"] = "5%"; parent.Controls.Add(v); return(v); }
protected override BaseValidator CreateWebValidator() { RegularExpressionValidator webValidator = new RegularExpressionValidator(); this.AssociateControl(webValidator); webValidator.ValidationExpression = "^.{" + this.Validator.Minimum.ToString() + "," + this.Validator.Maximum.ToString() + "}$"; return webValidator; }
public static RegularExpressionValidator RegExpression(string message, string target, string expression) { RegularExpressionValidator regField = new RegularExpressionValidator(); regField.ErrorMessage = message + " is invalid"; regField.ControlToValidate = target; regField.ValidationExpression = expression; regField.EnableClientScript = false; regField.Display = ValidatorDisplay.None; return(regField); }
private RegularExpressionValidator GenerateDateREV(Control control) { RegularExpressionValidator rev = new RegularExpressionValidator(); rev.ControlToValidate = control.ID; rev.Display = ValidatorDisplay.Dynamic; rev.ValidationExpression = @"(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20|21)\d\d"; rev.Text = "* Date is in the wrong format"; return(rev); }
private void CreateRegularExpression(RegularExpressionValidationAttribute attr, string name) { RegularExpressionValidator validator = new RegularExpressionValidator(); validator.ID = "rev" + ControlToValidate; validator.ControlToValidate = ControlToValidate; validator.ValidationExpression = attr.RegularExpression; validator.Text = defaultText; validator.ErrorMessage = string.Format(attr.Message, name);; validator.Display = ValidatorDisplay.Dynamic; Controls.Add(validator); }
protected override void CreateChildControls() { Controls.Clear(); captionLiteral = new Literal(); inputTextBox = new TextBox(); inputTextBox.ID = "inputTextBox"; //inputTextBox.ValidationGroup = ValidationGroup; reqValidator = new RequiredFieldValidator(); reqValidator.ID = "valReq" + inputTextBox.ID; reqValidator.ControlToValidate = inputTextBox.ID; reqValidator.ToolTip = ReqToolTip; reqValidator.Display = ValidatorDisplay.Dynamic; reqValidator.SetFocusOnError = true; //reqValidator.ValidationGroup = ValidationGroup; reqValidator.CssClass = "validator-trigger"; regValidator = new RegularExpressionValidator(); regValidator.ID = "valReg" + inputTextBox.ID; regValidator.ControlToValidate = inputTextBox.ID; regValidator.ToolTip = RegToolTip; regValidator.Display = ValidatorDisplay.Dynamic; regValidator.SetFocusOnError = true; //regValidator.ValidationGroup = ValidationGroup; regValidator.CssClass = "validator-trigger"; regValidator.ValidationExpression = @"^(((0[1-9]|[12][0-9]|3[01])([\.])(0[13578]|10|12)([\.])((19[0-9][0-9])|(2[0-9][0-9][0-9])))|(([0][1-9]|[12][0-9]|30)([\.])(0[469]|11)([\.])((19[0-9][0-9])|(2[0-9][0-9][0-9])))|((0[1-9]|1[0-9]|2[0-8])([\.])(02)([\.])((19[0-9][0-9])|(2[0-9][0-9][0-9])))|((29)([\.])(02)([\.])([02468][048]00))|((29)([\.])(02)([\.])([13579][26]00))|((29)([\.])(02)([\.])([0-9][0-9][0][48]))|((29)([\.])(02)([\.])([0-9][0-9][2468][048]))|((29)([\.])(02)([\.])([0-9][0-9][13579][26])))$"; if (DataType != InputType.None) { inputTextBox.CausesValidation = true; } if (DataType == InputType.Date) { inputTextBox.CssClass = "datepicker"; } this.Controls.Add(captionLiteral); this.Controls.Add(inputTextBox); //if (DataType != InputType.None) this.Controls.Add(reqValidator); //if (DataType == InputType.Date) this.Controls.Add(regValidator); //ClearChildViewState(); }
new protected void Page_Load(object sender, EventArgs e) { Page.DataBind(); _gradeUiMapping = new GradeUiMapping(); string purchaseIdString = Request["ID"]; if (!int.TryParse(purchaseIdString, out _purchaseID)) { Response.Redirect(Pages.InfoPage + "?ID=" + InfoMessages.PurchaseNotFound.ToString()); } if (!IsPostBack) { _gradeUiMapping.PopulateGradeDropDownList(DropDownListGrade); GasPurchase purchase = GasPurchasesDBRetriever.GetPurchase(Context.User.Identity.Name, _purchaseID); if (purchase == null) { Response.Redirect(Pages.InfoPage + "?ID=" + InfoMessages.PurchaseNotFound.ToString()); } Calendar.SelectedDate = purchase.When; Calendar.VisibleDate = Calendar.SelectedDate; PriceTextBox.Text = purchase.Price.ToString(); AmountTextBox.Text = purchase.Amount.ToString(); DistanceTextBox.Text = purchase.Distance.ToString(); int gradeIndex = _gradeUiMapping.GradeToIndex(purchase.GradeOfFuel); DropDownListGrade.SelectedIndex = gradeIndex; NoteTextBox.Text = purchase.Note; } RegularExpressionValidator priceValidator = (RegularExpressionValidator)Page.FindControl("RegularExpression_PriceValidator"); if (priceValidator != null) { priceValidator.ValidationExpression = RegExpr_NNNN_nn; } RegularExpressionValidator amountValidator = (RegularExpressionValidator)Page.FindControl("RegularExpression_AmountValidator"); if (amountValidator != null) { amountValidator.ValidationExpression = RegExpr_NNNN_nn; } RegularExpressionValidator distanceValidator = (RegularExpressionValidator)Page.FindControl("RegularExpression_DistanceValidator"); if (distanceValidator != null) { distanceValidator.ValidationExpression = RegExpr_NNNN_nn; } }
private void ControlCreation() { ArrayList movieList = Mothercode.ShowMovies("%"); foreach (TblMovies movie in movieList) { Panel moviePanel = new Panel(); Image movieimage = new Image { ImageUrl = movie.MovieImage, CssClass = "ProductsImage" }; Literal literalno1 = new Literal { Text = "<br />" }; Literal literalno2 = new Literal { Text = "<br />" }; Label movienamelabel = new Label { Text = movie.MovieName, CssClass = "ProductsName" }; Label moviepricelabel = new Label { Text = String.Format("{0:0.00}", "$" + movie.TotalPrice + "<br />"), CssClass = "ProductsPrice" }; TextBox textBox = new TextBox { ID = "txtbox" + Guid.NewGuid().ToString("N"), CssClass = "ProductsTextBox", Width = 60, Text = "0" }; RegularExpressionValidator regex = new RegularExpressionValidator { ValidationExpression = "^[0-9]*", ControlToValidate = textBox.ID, ErrorMessage = "Please enter a number." }; moviePanel.Controls.Add(movieimage); moviePanel.Controls.Add(literalno1); moviePanel.Controls.Add(movienamelabel); moviePanel.Controls.Add(literalno2); moviePanel.Controls.Add(moviepricelabel); moviePanel.Controls.Add(textBox); moviePanel.Controls.Add(regex); pnlProducts.Controls.Add(moviePanel); } }
/// <summary> /// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering. /// </summary> protected override void CreateChildControls() { base.CreateChildControls(); _regexValidator = new RegularExpressionValidator(); _regexValidator.ID = this.ID + "_RE"; _regexValidator.ControlToValidate = this.ID; _regexValidator.Display = ValidatorDisplay.Dynamic; _regexValidator.CssClass = "validation-error help-inline"; _regexValidator.ValidationExpression = GetUrlRegEx(); _regexValidator.ErrorMessage = GetValidationErrorMessage(); Controls.Add(_regexValidator); }
protected List <WebControl> GetTextBoxControls(string id, string labelText, string validationGroup, bool required, string requiredErrorMessage, string regexFormatErrorMessage, string regexLengthErrorMessage, string regexPattern, string regexLengthPattern) { List <WebControl> controls = GetTextBoxControls(id, labelText, validationGroup, required, requiredErrorMessage, regexFormatErrorMessage, regexPattern); string textBoxID = controls[0].ID; RegularExpressionValidator regularExpressionValidator = GetValidator <RegularExpressionValidator>(new RegularExpressionValidator(), _regexPrefix + id + _lengthSuffix, textBoxID, regexLengthErrorMessage, validationGroup, ValidatorDisplay.Dynamic); regularExpressionValidator.ValidationExpression = regexLengthPattern; return(controls); }
protected void btnActCodeSender_Click(object sender, EventArgs e) { RequiredEmail.Validate(); RegularExpressionValidator.Validate(); if (RegularExpressionValidator.IsValid && RequiredEmail.IsValid) { _actCode = TextHelper.RandomNumber(4); Email.SendGmail("*****@*****.**", "ma8635047", email.Value, "Mã kích hoạt đăng ký", $"Mã kích hoạt của bạn là {_actCode}"); Alert($"alert('Đã gửi mã kích hoạt đến {email.Value}')"); } }
/// <summary> /// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering. /// </summary> protected override void CreateChildControls() { base.CreateChildControls(); _regexValidator = new RegularExpressionValidator(); _regexValidator.ID = this.ID + "_RE"; _regexValidator.ControlToValidate = this.ID; _regexValidator.Display = ValidatorDisplay.Dynamic; _regexValidator.CssClass = "validation-error help-inline"; _regexValidator.ValidationExpression = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"; _regexValidator.ErrorMessage = "The email address provided is not valid"; Controls.Add(_regexValidator); }
private void AddRegExValidator() { RegularExpressionValidator = new RegularExpressionValidator() { ControlToValidate = TextBox.ID, ErrorMessage = ErrorMessage, Display = ValidatorDisplay.Dynamic, ID = "reg" + regCount++.ToString(), CssClass = ValidatorCssClass, ValidationExpression = RegEx, }; ValidationPlaceHolder.Controls.Add(RegularExpressionValidator); }
private void AddRegexValidation(Control control, string regularExpression, string text, string errorMessage) { RegularExpressionValidator rev = new RegularExpressionValidator(); rev.ControlToValidate = control.ID; rev.ValidationExpression = regularExpression; rev.ErrorMessage = string.Format(errorMessage, this.Label); rev.Text = text; rev.Display = ValidatorDisplay.Dynamic; rev.ValidationGroup = ValidationGroup; rev.CssClass = ValidationCssClass; this.Controls.Add(rev); }
protected void Page_Load(object sender, EventArgs e) { RegularExpressionValidator reg = new RegularExpressionValidator(); reg.ID = "RegularExpressionValidator1"; reg.ControlToValidate = "TextBox1"; reg.Display = ValidatorDisplay.Dynamic; reg.ErrorMessage = "your Error message"; reg.SetFocusOnError = true; reg.ValidationExpression = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"; form1.Controls.Add(reg); reg.Validate(); }
public bool Validar(bool validarControlInterno) { if (validarControlInterno) { RequiredFieldValidator valRequeridoCalle = (RequiredFieldValidator)this.phValidCalle.FindControl("valRequeridoCalle"); RegularExpressionValidator valDescripcionCalle = (RegularExpressionValidator)this.phValidCalle.FindControl("valDescripcionCalle"); RegularExpressionValidator valEnteroNroCalle = (RegularExpressionValidator)this.phValidCalleNro.FindControl("valEnteroNroCalle"); //RequiredFieldValidator valRequeridoTelefono = (RequiredFieldValidator)this.phValidTelefono.FindControl("valRequeridoTelefono"); //RequiredFieldValidator valRequeridoProvincia = (RequiredFieldValidator)this.phValidCalle.FindControl("valRequeridoProvincia"); //RequiredFieldValidator valRequeridoLocalidad = (RequiredFieldValidator)this.phValidCalle.FindControl("valRequeridoLocalidad"); CustomValidator cstmValidatorProvincia = (CustomValidator)phValidProvincia.FindControl("cstmValidatorProvincia"); CustomValidator cstmValidatorLocalidad = (CustomValidator)phValidLocalidad.FindControl("cstmValidatorLocalidad"); valRequeridoCalle.Enabled = true; valDescripcionCalle.Enabled = true; valEnteroNroCalle.Enabled = true; //valRequeridoTelefono.Enabled = true; cstmValidatorProvincia.Enabled = true; cstmValidatorLocalidad.Enabled = true; valRequeridoCalle.Validate(); valDescripcionCalle.Validate(); valEnteroNroCalle.Validate(); //valRequeridoTelefono.Validate(); cstmValidatorProvincia.Validate(); cstmValidatorLocalidad.Validate(); if (valRequeridoCalle.IsValid && valDescripcionCalle.IsValid && valEnteroNroCalle.IsValid && cstmValidatorProvincia.IsValid && cstmValidatorLocalidad.IsValid) { return(true); } else { return(false); } } else { RequiredFieldValidator valRequeridoCalle = (RequiredFieldValidator)this.phValidCalle.FindControl("valRequeridoCalle"); RegularExpressionValidator valDescripcionCalle = (RegularExpressionValidator)this.phValidCalle.FindControl("valDescripcionCalle"); RegularExpressionValidator valEnteroNroCalle = (RegularExpressionValidator)this.phValidCalleNro.FindControl("valEnteroNroCalle"); //RequiredFieldValidator valRequeridoTelefono = (RequiredFieldValidator)this.phValidTelefono.FindControl("valRequeridoTelefono"); RequiredFieldValidator valRequeridoProvincia = (RequiredFieldValidator)this.phValidCalle.FindControl("valRequeridoProvincia"); RequiredFieldValidator valRequeridoLocalidad = (RequiredFieldValidator)this.phValidCalle.FindControl("valRequeridoLocalidad"); valRequeridoCalle.Enabled = false; valDescripcionCalle.Enabled = false; valEnteroNroCalle.Enabled = false; //valRequeridoTelefono.Enabled = true; valRequeridoProvincia.Enabled = false; valRequeridoLocalidad.Enabled = false; return(true); } }
public Empleado Modificar() { Empleado emp = new Empleado(); String valor = Request.QueryString["id"]; int id = int.Parse(valor); emp.Id_Empleado = id; if (Mnombre.ToString() == null) //valido los campos que no sean nulos { Mnombre.BorderColor = System.Drawing.Color.Red; //si son nulos, me tirara un error de validacion } else { emp.Nombre_Empleado = Mnombre.Text; //si son validos, me dejara enviar los datos a la base de datoa } if (Mapellido.ToString() == null) //todo esto se hace para todos los campos del formulario { RegularExpressionValidator.GetValidationProperty(RequiredFieldValidator1); } else { emp.Apellido = Mapellido.Text; } if (Mcedula.ToString() == null) { RegularExpressionValidator.GetValidationProperty(RequiredFieldValidator1); } else { emp.Cedula = Mcedula.Text; } if (Mcargo.SelectedValue == null)//todo esto se hace para todos los campos del formulario { RegularExpressionValidator.GetValidationProperty(RequiredFieldValidator1); } else { emp.Cargo = Mcargo.SelectedValue; } // ord.Tipo_caso = Mtipocaso.SelectedValue; //ord.Tipo_orden = Mtipoorden.SelectedValue; //ord.Observaciones = Mobservaciones.Text; // ord.Baucher = Mbaucher.Text; // ord.No_orden = int.Parse(Mnoorden.Text); // ord.Estado = Mestado.SelectedValue; return(emp); }
protected override void CreateChildControls() { base.CreateChildControls(); tb_Input = new TextBox(); tb_Input.ID = "tb_Input"; regexVal = new RegularExpressionValidator(); regexVal.ValidationExpression = field.Regex; regexVal.ControlToValidate = "tb_Input"; regexVal.Text = "Input invalid!"; this.Controls.Add(tb_Input); this.Controls.Add(regexVal); }
public Muestra Modificar() { if (Mmuestra.ToString() == null) { RegularExpressionValidator.GetValidationProperty(RequiredFieldValidator2); } else { mue.muestra = Mmuestra.Text; } return(mue); }
private void hFile_DataBinding(object sender, EventArgs e) { HtmlInputFile hFile = (HtmlInputFile)sender; hFile.Size = intWidth; if (blValidation == true) { RegularExpressionValidator rgv = new RegularExpressionValidator(); rgv.ControlToValidate = "hFile"; rgv.Display = ValidatorDisplay.None; rgv.ErrorMessage = "Please Select the File names of the type : " + strExpr; rgv.ValidationExpression = @"^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(" + @strExpr + ")$"; } }
public void WithNonString() { RegularExpressionValidator validator = new RegularExpressionValidator(); validator.Validate(this, new ValidationErrors()); }
public void AllowPartialMatching() { RegularExpressionValidator validator = new RegularExpressionValidator(); validator.Expression = "[A-Za-z]"; validator.AllowPartialMatching = true; Assert.True(validator.Validate("123a456", new ValidationErrors())); }
protected void Page_Load(object sender, EventArgs e) { SuperForm1 = new SuperForm(); SuperForm1.ID = "SuperForm1"; SuperForm1.DataSourceID = "SqlDataSource1"; SuperForm1.AutoGenerateRows = false; SuperForm1.AutoGenerateInsertButton = true; SuperForm1.AutoGenerateEditButton = true; SuperForm1.AutoGenerateDeleteButton = true; SuperForm1.DataKeyNames = new string[] { "EmployeeID" }; SuperForm1.AllowPaging = true; SuperForm1.ValidationGroup = "Group1"; SuperForm1.DefaultMode = DetailsViewMode.Insert; SuperForm1.ItemCommand += SuperForm1_ItemCommand; Obout.SuperForm.BoundField field1 = new Obout.SuperForm.BoundField(); field1.DataField = "EmployeeID"; field1.HeaderText = "Employee ID"; field1.ReadOnly = true; field1.InsertVisible = false; RequiredFieldValidator field2Required = new RequiredFieldValidator(); field2Required.ID = "FirstNameValidator"; field2Required.Display = ValidatorDisplay.None; field2Required.ErrorMessage = "First Name is mandatory"; ValidatorCalloutExtender field2CalloutExtender = new ValidatorCalloutExtender(); field2CalloutExtender.ID = "FirstNameValidatorCallout"; field2CalloutExtender.TargetControlID = "FirstNameValidator"; field2CalloutExtender.Width = 250; field2CalloutExtender.HighlightCssClass = "highlight"; field2CalloutExtender.WarningIconImageUrl = "resources/icons/warning.gif"; field2CalloutExtender.CloseImageUrl = "resources/icons/close.gif"; Obout.SuperForm.BoundField field2 = new Obout.SuperForm.BoundField(); field2.DataField = "FirstName"; field2.HeaderText = "First Name"; field2.Validators.Add(field2Required); field2.Validators.Add(field2CalloutExtender); RequiredFieldValidator field3Required = new RequiredFieldValidator(); field3Required.ID = "LastNameValidator"; field3Required.Display = ValidatorDisplay.None; field3Required.ErrorMessage = "Last Name is mandatory"; field3Required.Text = "*"; ValidatorCalloutExtender field3CalloutExtender = new ValidatorCalloutExtender(); field3CalloutExtender.ID = "LastNameValidatorCallout"; field3CalloutExtender.TargetControlID = "LastNameValidator"; field3CalloutExtender.Width = 250; field3CalloutExtender.HighlightCssClass = "highlight"; field3CalloutExtender.WarningIconImageUrl = "resources/icons/warning.gif"; field3CalloutExtender.CloseImageUrl = "resources/icons/close.gif"; Obout.SuperForm.BoundField field3 = new Obout.SuperForm.BoundField(); field3.DataField = "LastName"; field3.HeaderText = "Last Name"; field3.Validators.Add(field3Required); field3.Validators.Add(field3CalloutExtender); RequiredFieldValidator field4Required = new RequiredFieldValidator(); field4Required.ID = "TitleOfCourtesyValidator1"; field4Required.Display = ValidatorDisplay.None; field4Required.ErrorMessage = "Courtesy Title is mandatory"; field4Required.Text = "*"; ValidatorCalloutExtender field4Callout1 = new ValidatorCalloutExtender(); field4Callout1.ID = "TitleOfCourtesyValidatorCallout1"; field4Callout1.TargetControlID = "TitleOfCourtesyValidator1"; field4Callout1.Width = 250; field4Callout1.HighlightCssClass = "highlight"; field4Callout1.WarningIconImageUrl = "resources/icons/warning.gif"; field4Callout1.CloseImageUrl = "resources/icons/close.gif"; CustomValidator field4Custom = new CustomValidator(); field4Custom.ID = "TitleOfCourtesyValidator2"; field4Custom.ServerValidate += ValidateTitle; field4Custom.Display = ValidatorDisplay.Dynamic; field4Custom.ErrorMessage = "Courtesy Title needs to be 'Mr.', 'Ms.', 'Mrs.' or 'Dr.'"; field4Custom.Text = "Courtesy Title needs to be 'Mr.', 'Ms.', 'Mrs.' or 'Dr.'"; Obout.SuperForm.BoundField field4 = new Obout.SuperForm.BoundField(); field4.DataField = "TitleOfCourtesy"; field4.HeaderText = "Courtesy Title"; field4.Validators.Add(field4Required); field4.Validators.Add(field4Callout1); field4.Validators.Add(field4Custom); RequiredFieldValidator field5Required = new RequiredFieldValidator(); field5Required.ID = "BirthDateValidator1"; field5Required.Display = ValidatorDisplay.None; field5Required.ErrorMessage = "Birth Date is mandatory"; field5Required.Text = "*"; ValidatorCalloutExtender field5Callout1 = new ValidatorCalloutExtender(); field5Callout1.ID = "BirthDateValidatorCallout1"; field5Callout1.TargetControlID = "BirthDateValidator1"; field5Callout1.Width = 250; field5Callout1.HighlightCssClass = "highlight"; field5Callout1.WarningIconImageUrl = "resources/icons/warning.gif"; field5Callout1.CloseImageUrl = "resources/icons/close.gif"; RangeValidator field5Range = new RangeValidator(); field5Range.ID = "BirthDateValidator2"; field5Range.Display = ValidatorDisplay.None; field5Range.MinimumValue = "1900/1/1"; field5Range.MaximumValue = "2039/12/31"; field5Range.Type = ValidationDataType.Date; field5Range.ErrorMessage = "Birth Date needs to be in this format: mm/dd/yyyy"; field5Range.Text = "*"; ValidatorCalloutExtender field5Callout2 = new ValidatorCalloutExtender(); field5Callout2.ID = "BirthDateValidatorCallout2"; field5Callout2.TargetControlID = "BirthDateValidator2"; field5Callout2.Width = 250; field5Callout2.HighlightCssClass = "highlight"; field5Callout2.WarningIconImageUrl = "resources/icons/warning.gif"; field5Callout2.CloseImageUrl = "resources/icons/close.gif"; Obout.SuperForm.DateField field5 = new Obout.SuperForm.DateField(); field5.DataField = "BirthDate"; field5.HeaderText = "Birth Date"; field5.DataFormatString = "{0:MM/dd/yyyy}"; field5.ApplyFormatInEditMode = true; field5.Validators.Add(field5Required); field5.Validators.Add(field5Callout1); field5.Validators.Add(field5Range); field5.Validators.Add(field5Callout2); RequiredFieldValidator field6Required = new RequiredFieldValidator(); field6Required.ID = "HomePhoneValidator1"; field6Required.Display = ValidatorDisplay.None; field6Required.ErrorMessage = "Home Phone is mandatory"; field6Required.Text = "*"; ValidatorCalloutExtender field6Callout1 = new ValidatorCalloutExtender(); field6Callout1.ID = "HomePhoneValidatorCallout1"; field6Callout1.TargetControlID = "HomePhoneValidator1"; field6Callout1.Width = 250; field6Callout1.HighlightCssClass = "highlight"; field6Callout1.WarningIconImageUrl = "resources/icons/warning.gif"; field6Callout1.CloseImageUrl = "resources/icons/close.gif"; RegularExpressionValidator field6Range = new RegularExpressionValidator(); field6Range.ID = "HomePhoneValidator2"; field6Range.Display = ValidatorDisplay.None; field6Range.ValidationExpression = "^(\\(?\\s*\\d{3}\\s*[\\)\\-\\.]?\\s*)?[1-9]\\d{2}\\s*[\\-\\.]\\s*\\d{4}$"; field6Range.ErrorMessage = "Home Phone must be in this format (###) ###-####"; field6Range.Text = "*"; ValidatorCalloutExtender field6Callout2 = new ValidatorCalloutExtender(); field6Callout2.ID = "HomePhoneValidatorCallout2"; field6Callout2.TargetControlID = "HomePhoneValidator2"; field6Callout2.Width = 250; field6Callout2.HighlightCssClass = "highlight"; field6Callout2.WarningIconImageUrl = "resources/icons/warning.gif"; field6Callout2.CloseImageUrl = "resources/icons/close.gif"; Obout.SuperForm.BoundField field6 = new Obout.SuperForm.BoundField(); field6.DataField = "HomePhone"; field6.HeaderText = "Home Phone"; field6.Validators.Add(field6Required); field6.Validators.Add(field6Callout1); field6.Validators.Add(field6Range); field6.Validators.Add(field6Callout2); SuperForm1.Fields.Add(field1); SuperForm1.Fields.Add(field2); SuperForm1.Fields.Add(field3); SuperForm1.Fields.Add(field4); SuperForm1.Fields.Add(field5); SuperForm1.Fields.Add(field6); SuperForm1Container.Controls.Add(SuperForm1); }
public void Should_create_regularexpressionadapter_for_regularexpressionvalidator() { // Given var validator = new RegularExpressionValidator("[A-Z]*"); // When var result = factory.Create(this.rule, validator); // Then result.ShouldBeOfType<RegularExpressionAdapter>(); }
public void WhitespaceStringDoesntEvaluateToTrueByDefault() { RegularExpressionValidator validator = new RegularExpressionValidator(); Assert.IsFalse(validator.Validate(" ", new ValidationErrors())); }
protected void Page_Init(System.Object sender, System.EventArgs e) { EnableMultilingual = AppUI.EnableMultilingual; cContObj = new EkContent(m_refContentApi.RequestInformationRef); objTask = new EkTask(m_refContentApi.RequestInformationRef); MsgHelper = new EkMessageHelper(m_refContentApi.RequestInformationRef); objTaskType = new Ektron.Cms.Content.EkTaskType(m_refContentApi.RequestInformationRef); usrObj = new Ektron.Cms.User.EkUser(m_refContentApi.RequestInformationRef); GenerateJS(); ltrStyleHelper.Text = m_refStyle.GetClientScript(); ltrEmailScript.Text = m_EmailHelper.EmailJS(); FillLiterals(); ctlEditor = (Ektron.ContentDesignerWithValidator)LoadControl("controls/Editor/ContentDesignerWithValidator.ascx"); ctlEditor.ID = "description"; ctlEditor.AllowScripts = true; ctlEditor.Height = new Unit(450, UnitType.Pixel); ctlEditor.Width = new Unit(100, UnitType.Percentage); ctlEditor.ToolsFile = m_refContentApi.ApplicationPath + "ContentDesigner/configurations/InterfaceTask.xml"; ctlEditor.AllowFonts = true; ctlEditor.ShowHtmlMode = false; ctlEditor.Stylesheet = m_refContentApi.ApplicationPath + "csslib/ewebeditprostyles.css"; RegularExpressionValidator ctlValidator = new RegularExpressionValidator(); Ektron.Cms.Common.EkMessageHelper m_refMsg = m_refSiteApi.EkMsgRef; ctlValidator.ID = "RegExpValidator"; ctlValidator.ControlToValidate = "description"; ctlValidator.ErrorMessage = m_refMsg.GetMessage("content size exceeded"); ctlValidator.ValidationExpression = Utilities.BuildRegexToCheckMaxLength(int.Parse(iMaxContLength)); Action = EkFunctions.HtmlEncode(Request.QueryString["action"]); if ("AddTask" == Action) { AddTaskValidatorHolder.Controls.Add(ctlValidator); AddTaskEditorHolder.Controls.Add(ctlEditor); } else if ("EditTask" == Action) { EditTaskValidatorHolder.Controls.Add(ctlValidator); EditTaskEditorHolder.Controls.Add(ctlEditor); } if (Request.QueryString["page"] != null) { CurrentPage = EkFunctions.ReadIntegerValue(Request.QueryString["page"], 1); } }
protected void Page_Load(object sender, EventArgs e) { HttpCookie cookie = Request.Cookies["BrowserDate"]; //Ajax.Utility.RegisterTypeForAjax(typeof(Coaches_MessageAlert)); SendItButton.SERVER_CLICK += SendIt; FlagButton.SERVER_CLICK += SendFlagEmail; BlueButton3.SERVER_CLICK += SendEmail; BlueButton5.SERVER_CLICK += AddVenue; BlueButton7.SERVER_CLICK += SendMessage; if (cookie != null) { if (!IsPostBack) { string type = Request.QueryString["T"].ToString(); Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":"))); string phone = ""; string providerExtension = ""; try { if (Session["User"] != null) { DataView dvUser = dat.GetDataDV("SELECT * FROM Users WHERE User_ID=" + Session["User"].ToString()); phone = dvUser[0]["PhoneNumber"].ToString(); providerExtension = dat.GetDataDV("SELECT Extension FROM PhoneProviders WHERE id=" + dvUser[0]["PhoneProvider"].ToString())[0]["Extension"].ToString(); DataSet ds = dat.GetData("SELECT CommunicationPrefs FROM UserPreferences WHERE UserID=" + Session["User"].ToString()); if (ds.Tables[0].Rows[0]["CommunicationPrefs"].ToString() == "1") Session["On"] = true; else Session["On"] = false; } else { TechLiteral.Text = "<script type=\"text/javascript\">Search('../login');</script>"; Session["On"] = false; } } catch (Exception ex) { Session["On"] = false; } MessageTextBox.Text = ""; Encryption decrypt = new Encryption(); switch (type) { case "Connect": MessagePanel.Visible = true; if (Request.QueryString["Subject"] != null) SubjectLabel.Text = Request.QueryString["Subject"].ToString(); else SubjectLabel.Text = Session["Subject"].ToString(); SubjectLabelPanel.Visible = true; CalendarPanel.Visible = false; TextPanel.Visible = false; VenuePanel.Visible = false; break; case "ConnectTrip": DataSet dsAd = dat.GetData("SELECT * FROM Trips T, Users U WHERE T.UserName=U.UserName AND T.ID=" + Request.QueryString["ID"].ToString()); string subject = dsAd.Tables[0].Rows[0]["UserName"].ToString() + " would like to inquire into \"" + dsAd.Tables[0].Rows[0]["Header"].ToString() + "\""; MessagePanel.Visible = true; SubjectLabel.Text = subject; SubjectLabelPanel.Visible = true; CalendarPanel.Visible = false; TextPanel.Visible = false; VenuePanel.Visible = false; break; case "Message": MessageTextBox.Text = ""; MessagePanel.Visible = true; if (Session["Subject"] != null) if (Session["Subject"].ToString() != "") { if (Request.QueryString["a"] != "") { SubjectLabelPanel.Visible = true; SubjectLabel.Text = Session["Subject"].ToString(); if (Request.QueryString["a"] == "ConnectTrip") { DataSet dsAd2 = dat.GetData("SELECT * FROM Trips T, Users U WHERE T.UserName=U.UserName AND T.ID=" + Request.QueryString["ID"].ToString()); string subject2 = dsAd2.Tables[0].Rows[0]["UserName"].ToString() + " would like to inquire into \"" + dsAd2.Tables[0].Rows[0]["Header"].ToString() + "\""; SubjectLabel.Text = subject2; } } else { SubjectTextBoxPanel.Visible = true; ErrorLabel.Visible = true; Session["Subject"] = ""; } } else { SubjectTextBoxPanel.Visible = true; ErrorLabel.Visible = true; Session["Subject"] = ""; } else { SubjectTextBoxPanel.Visible = true; ErrorLabel.Visible = true; Session["Subject"] = ""; } if (Request.QueryString["a"].ToString() == "a") Session["ViewedUser"] = dat.GetData("SELECT User_ID FROM Ads WHERE Ad_ID=" + Request.QueryString["ID"].ToString()).Tables[0].Rows[0]["User_ID"].ToString(); else Session["ViewedUser"] = Request.QueryString["ID"].ToString(); CalendarPanel.Visible = false; TextPanel.Visible = false; VenuePanel.Visible = false; break; case "Comment": MessageTextBox.Text = ""; MessagePanel.Visible = true; if (Session["CommentSubject"] != null) if (Session["CommentSubject"].ToString() != "") { SubjectLabelPanel.Visible = true; SubjectLabel.Text = Session["CommentSubject"].ToString(); } else { SubjectTextBoxPanel.Visible = true; ErrorLabel.Visible = true; Session["CommentSubject"] = ""; } else { SubjectTextBoxPanel.Visible = true; ErrorLabel.Visible = true; Session["CommentSubject"] = ""; } Session["ViewedUser"] = Request.QueryString["ID"].ToString(); ; CalendarPanel.Visible = false; TextPanel.Visible = false; VenuePanel.Visible = false; break; case "Calendar": CalendarPanel.Visible = true; MessagePanel.Visible = false; TextPanel.Visible = false; VenuePanel.Visible = false; ConnectCheckBox.Checked = false; if (bool.Parse(Session["On"].ToString())) ConnectCheckBox.Visible = true; else ConnectCheckBox.Visible = false; break; case "Txt": string message = Session["messageText"].ToString(); if (phone != "0") PhoneTextBox.Text = phone; ProvidersDropDown.DataBind(); ProvidersDropDown.SelectedValue = providerExtension; TextPanel.Visible = true; MessagePanel.Visible = false; CalendarPanel.Visible = false; VenuePanel.Visible = false; TxtMessageTextBox.Text = message; break; case "Venue": MessagePanel.Visible = false; CalendarPanel.Visible = false; TextPanel.Visible = false; VenuePanel.Visible = true; TechLiteral.Text = "<div id=\"TechDiv\" style=\"display: none;\">" + Request.QueryString["ID"].ToString() + "</div>"; break; case "Email": if (Session["User"] != null) { //DataSet dsuser = dat.GetData("SELECT * FROM Users WHERE User_ID=" + Session["User"].ToString()); //YourEmailTextBox.Text = dsuser.Tables[0].Rows[0]["Email"].ToString(); //YourEmailTextBox.Enabled = false; RequiredFieldValidatorEmail.IsValid = false; } else { RequiredFieldValidatorEmail.IsValid = false; } EmailSubjectLabel.Text = "Hippo Happenings Info"; MessagePanel.Visible = false; CalendarPanel.Visible = false; TextPanel.Visible = false; VenuePanel.Visible = false; EmailPanel.Visible = true; break; case "Flag": FlagSubject.Text = "Hippo Happenings Flag!"; if (Session["User"] == null) { FlagTextPanel.Visible = true; RequiredFieldValidator r = new RequiredFieldValidator(); r.ID = "RequiredFieldValidator3"; r.CssClass = "AddGreenLink"; r.ErrorMessage = "*Email is required"; r.ControlToValidate = "FlagEmailTextBox"; r.IsValid = false; FlagTextPanel.Controls.Add(r); RegularExpressionValidator t = new RegularExpressionValidator(); t.ID = "RegularExpressionValidator1"; t.CssClass = "AddGreenLink"; t.ErrorMessage = "*Email is not valid"; t.ValidationExpression = "^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2,4})$"; t.ControlToValidate = "FlagEmailTextBox"; FlagTextPanel.Controls.Add(t); } MessagePanel.Visible = false; CalendarPanel.Visible = false; TextPanel.Visible = false; VenuePanel.Visible = false; EmailPanel.Visible = false; FlagPanel.Visible = true; break; default: break; } } } else { TechLiteral.Text = "<script type=\"text/javascript\">Search('../login');</script>"; } if (!IsPostBack) { Session["VenueAdded"] = null; } }
public void WithNull() { RegularExpressionValidator validator = new RegularExpressionValidator(); Assert.Throws<ArgumentException>(() => validator.Validate(null, new ValidationErrors())); }
protected void Page_Load(object sender, EventArgs e) { if (Session["Organiser"] == null || Session["EventID"] == null) Response.Redirect("~/Login.aspx"); else { Organiser organiser = (Organiser)Session["Organiser"]; ev = Event.GetEventDetails(int.Parse(Session["EventID"].ToString())); lblEventName.Text = ev.Name; if (ev.IsSinglePlayer) lblEventType.Text = "Single Player Game."; else lblEventType.Text = "Multi Player Game."; Page.Title = organiser.Society + "- " + ev.Name; for (int i = 0; i < ev.MaxTeamSize; i++) { TextBox tb = new TextBox(); tb.ID = "TTID" + (i + 1).ToString(); tb.Attributes.Add("placeholder", "TTID " + (i + 1).ToString()); pnlTxtBx.Controls.Add(tb); RegularExpressionValidator rev = new RegularExpressionValidator(); rev.ControlToValidate = tb.ClientID; rev.ValidationExpression = "\\d{4}"; rev.ErrorMessage = "*"; pnlTxtBx.Controls.Add(rev); } } }
protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) { ev = Event.GetEventDetails(Team.GetEventID(int.Parse(txtbxTeamID.Text))); if (ev == null) { lblResult.Text = "Team does not exit."; return; } for (int i = 0; i < ev.MaxTeamSize; i++) { TextBox tb = new TextBox(); tb.ID = "TTID" + (i + 1).ToString(); tb.Attributes.Add("placeholder", "TTID " + (i + 1).ToString()); pnlTxtBx.Controls.Add(tb); RegularExpressionValidator rev = new RegularExpressionValidator(); rev.ControlToValidate = tb.ID; rev.ValidationExpression = "\\d{4}"; rev.ErrorMessage = "*"; pnlTxtBx.Controls.Add(rev); } } pnlTxtBx.Visible = false; btnUpdate.Visible = false; }
public void WithNull() { RegularExpressionValidator validator = new RegularExpressionValidator(); validator.Validate(null, new ValidationErrors()); }
public static void CreateDoubleValidator(RegularExpressionValidator fValidator, Control fControl) { fValidator.ValidationExpression = "^[0-9]+(.[0-9]{1,16})?$"; fValidator.ErrorMessage = "格式必须为数值"; fValidator.ControlToValidate = fControl.ID; //validator.EnableViewState = false; }
public void EmptyStringValidatesToTrue() { RegularExpressionValidator validator = new RegularExpressionValidator(); Assert.IsTrue(validator.Validate(string.Empty, new ValidationErrors())); }
public void When_validation_fails_the_default_error_should_be_set() { string input = "S33"; var validator = new RegularExpressionValidator(@"^\w\d$"); var result = validator.Validate(new PropertyValidatorContext("Name", new object(), x => input)); result.Single().ErrorMessage.ShouldEqual("'Name' is not in the correct format."); }
public void WhitespaceStringOnlyValidatesToTrueWhenGivenMatchingRegex() { RegularExpressionValidator validator = new RegularExpressionValidator(); validator.Expression = @"\s*"; Assert.IsTrue(validator.Validate(" ", new ValidationErrors())); }
public static void CreateIntegerValidator(RegularExpressionValidator fValidator, Control fControl) { fValidator.ValidationExpression = "^[0-9]*$"; fValidator.ErrorMessage = "格式必须为整数"; fValidator.ControlToValidate = fControl.ID; //validator.EnableViewState = false; }
public void SunnyDayFailure_Invalid() { RegularExpressionValidator validator = new RegularExpressionValidator(Expression.Parse("'ljwdf87cwbh'"), Expression.Parse("true"), @"((\d{1,2}\.\d{1,3}\.\d{1,3}\.\d{1,3}))"); Assert.IsFalse(validator.Validate("ljwdf87cwbh", new ValidationErrors())); }
public void SunnyDay_Valid() { RegularExpressionValidator validator = new RegularExpressionValidator(); validator.Expression = @"((\d{1,2}\.\d{1,3}\.\d{1,3}\.\d{1,3}))"; Assert.IsTrue(validator.Validate("11.222.333.444", new ValidationErrors())); }
public void CreateFields() { string tableName = ((System.Data.Linq.Mapping.TableAttribute)DataType.GetCustomAttributes(typeof(System.Data.Linq.Mapping.TableAttribute), false).First()).Name; MonkData db = new MonkData(); PropertyInfo[] properties = DataType.GetProperties(); // Look at each property on the object type foreach (PropertyInfo prop in properties) { Type propertyType = prop.PropertyType; object[] attributes = prop.GetCustomAttributes(false); if (attributes.Count() > 0) if (attributes[0].GetType() == typeof(ColumnAttribute)) { ColumnAttribute column = (ColumnAttribute)attributes[0]; if (column.DbType.Contains("Text")) { CreateFieldName(prop); CreateLineBreak(); // Show cool edit textbox FreeTextBoxControls.FreeTextBox textBox = new FreeTextBox(); textBox.Width = new Unit(920); textBox.Height = new Unit(350); textBox.ID = prop.Name; plcForm.Controls.Add(textBox); CreateLineBreak(); } else if (column.DbType.Contains("Decimal")) { CreateFieldName(prop); CreateLineBreak(); TextBox txtDecimal = new TextBox(); if (!Page.IsPostBack) txtDecimal.Text = "0.00"; txtDecimal.ID = prop.Name; plcForm.Controls.Add(txtDecimal); RequiredFieldValidator reqDecimal = new RequiredFieldValidator(); reqDecimal.ControlToValidate = prop.Name; reqDecimal.Text = "Required Decimal Number"; reqDecimal.ID = "reqDecimal_" + prop.Name; reqDecimal.ValidationGroup = "AddEdit"; plcForm.Controls.Add(reqDecimal); CreateLineBreak(); } else if (column.DbType.Contains("Bit")) { CheckBox chkBox = new CheckBox(); chkBox.ID = prop.Name; plcForm.Controls.Add(chkBox); CreateFieldName(prop); CreateLineBreak(); } else if (column.DbType.Contains("VarChar") || column.DbType.Contains("NChar")) { int maxLength = 8000; string number = column.DbType.Replace("NVarChar", "").Replace("NChar", "").Replace("VarChar", "").Replace("(", "").Replace(")", "").Replace(" NOT NULL", ""); if (number.Contains("N128")) { } if (number.Contains("MAX") || number.Contains("max")) { maxLength = 8000; } else { maxLength = int.Parse(number); } CreateFieldName(prop); CreateLineBreak(); // Get the max length of the varchar TextBox txtBox = new TextBox(); txtBox.ID = prop.Name; txtBox.MaxLength = maxLength; plcForm.Controls.Add(txtBox); CreateLineBreak(); } else if (column.DbType == "UniqueIdentifier") { // Don't show GUID columns } else if (column.DbType.Contains("DateTime")) { CreateFieldName(prop); CreateLineBreak(); // Get the max length of the varchar TextBox txtBox = new TextBox(); txtBox.ID = prop.Name; if (ItemId == null && !Page.IsPostBack) txtBox.Text = DateTime.Now.ToShortDateString(); plcForm.Controls.Add(txtBox); // Validate date information in box. RegularExpressionValidator regVal = new RegularExpressionValidator(); regVal.ID = "reg" + prop.Name; regVal.ControlToValidate = txtBox.ID; regVal.Text = "Must be in the format of '1:01 AM' or 23:52:01"; regVal.ValidationExpression = @"(?=\d)^(?:(?!(?:10\D(?:0?[5-9]|1[0-4])\D(?:1582))|(?:0?9\D(?:0?[3-9]|1[0-3])\D(?:1752)))((?:0?[13578]|1[02])|(?:0?[469]|11)(?!\/31)(?!-31)(?!\.31)|(?:0?2(?=.?(?:(?:29.(?!000[04]|(?:(?:1[^0-6]|[2468][^048]|[3579][^26])00))(?:(?:(?:\d\d)(?:[02468][048]|[13579][26])(?!\x20BC))|(?:00(?:42|3[0369]|2[147]|1[258]|09)\x20BC))))))|(?:0?2(?=.(?:(?:\d\D)|(?:[01]\d)|(?:2[0-8])))))([-.\/])(0?[1-9]|[12]\d|3[01])\2(?!0000)((?=(?:00(?:4[0-5]|[0-3]?\d)\x20BC)|(?:\d{4}(?!\x20BC)))\d{4}(?:\x20BC)?)(?:$|(?=\x20\d)\x20))?((?:(?:0?[1-9]|1[012])(?::[0-5]\d){0,2}(?:\x20[aApP][mM]))|(?:[01]\d|2[0-3])(?::[0-5]\d){1,2})?$"; regVal.ValidationGroup = "AddEdit"; plcForm.Controls.Add(regVal); // Add ajax popup calendar for date selection AjaxControlToolkit.CalendarExtender popupCal = new AjaxControlToolkit.CalendarExtender(); popupCal.ID = "popCal" + prop.Name; popupCal.TargetControlID = txtBox.ID; popupCal.Format = "MM/dd/yyyy"; plcForm.Controls.Add(popupCal); CreateLineBreak(); } else if (column.DbType.Contains("Int")) { int maxLength = 10; CreateFieldName(prop); CreateLineBreak(); TextBox txtBox = new TextBox(); txtBox.ID = prop.Name; txtBox.MaxLength = maxLength; if (!Page.IsPostBack) txtBox.Text = "0"; plcForm.Controls.Add(txtBox); RequiredFieldValidator reqInt = new RequiredFieldValidator(); reqInt.ID = "reqInt_" + prop.Name; reqInt.Text = "Required integer number"; reqInt.ControlToValidate = txtBox.ID; reqInt.ValidationGroup = "AddEdit"; plcForm.Controls.Add(reqInt); CreateLineBreak(); } } else if (attributes[0].GetType() == typeof(AssociationAttribute)) { // Load a dropdown list AssociationAttribute assocAttrib = (AssociationAttribute)attributes[0]; if (!String.IsNullOrEmpty(assocAttrib.ThisKey) && assocAttrib.IsForeignKey) { // The field that points to another table. PropertyInfo sourcePropertyInfo = DataType.GetProperties().First(p => p.Name == assocAttrib.ThisKey); // Create a dropdown list. DropDownList dropList = new DropDownList(); dropList.ID = prop.Name; // Get the type that is in the association that we're going to use. Type typeOfItems; typeOfItems = BuildManager.GetType("Monks." + prop.PropertyType.Name, true); // Get the primary key for that type PropertyInfo primaryKeyOfItems = GetPrimaryKeyProperty(typeOfItems); // Get the property from the table var matchingProperties = db.GetType().GetProperties().Where(p => p.Name.StartsWith(typeOfItems.Name.Substring(0, typeOfItems.Name.Length - 1))).OrderBy(p => p.Name.Length); if (matchingProperties.Count() < 1) continue; IEnumerable itemsInTable = (IEnumerable)matchingProperties.First().GetValue(db, null); if (sourcePropertyInfo.PropertyType.Name.Contains("Nullable")) dropList.Items.Add(new ListItem("null", "null")); string tableNameReferenceTable = ((System.Data.Linq.Mapping.TableAttribute)prop.PropertyType.GetCustomAttributes(typeof(System.Data.Linq.Mapping.TableAttribute), false).First()).Name; XmlNode xmlReferenceTableRules = GetDatabaseTable(prop.PropertyType.Name); XmlNode xmlDisplayPropertyName = null; if (xmlReferenceTableRules != null) xmlDisplayPropertyName = xmlReferenceTableRules.SelectSingleNode("TitleColumn"); // Loop over each item in the table foreach (object item in itemsInTable) { // If the column is a string, create the object. foreach (PropertyInfo itemPInfo in typeOfItems.GetProperties()) { if (xmlDisplayPropertyName != null) { if (xmlDisplayPropertyName.InnerText == itemPInfo.Name) { ListItem dListItem = new ListItem(); dListItem.Text = itemPInfo.GetValue(item, null).ToString().Replace(" ", " - "); dListItem.Value = primaryKeyOfItems.GetValue(item, null).ToString(); dropList.Items.Add(dListItem); break; } } else if (itemPInfo.PropertyType == typeof(string)) { ListItem dListItem = new ListItem(); if (itemPInfo.GetValue(item, null) == null) continue; dListItem.Text = itemPInfo.GetValue(item, null).ToString(); dListItem.Value = primaryKeyOfItems.GetValue(item, null).ToString(); dropList.Items.Add(dListItem); break; } } } CreateFieldName(prop); CreateLineBreak(); plcForm.Controls.Add(dropList); HyperLink hlNewItem = new HyperLink(); hlNewItem.Style.Add(HtmlTextWriterStyle.PaddingLeft, "10px"); hlNewItem.NavigateUrl = "AddEdit.aspx?typename=" + typeOfItems.Name; hlNewItem.Text = "Add New " + CreateFieldNameFromString(typeOfItems.Name); plcForm.Controls.Add(hlNewItem); Literal litSpace = new Literal(); litSpace.Text = " | "; plcForm.Controls.Add(litSpace); LinkButton lbtnViewCurrentSelectedItem = new LinkButton(); lbtnViewCurrentSelectedItem.Text = "View Selected Item"; lbtnViewCurrentSelectedItem.ID = "lbtnViewSelectedItem_" + prop.Name; lbtnViewCurrentSelectedItem.Click += new EventHandler(lbtnViewCurrentSelectedItem_Clicked); plcForm.Controls.Add(lbtnViewCurrentSelectedItem); Literal litSpace2 = new Literal(); litSpace2.Text = " | "; plcForm.Controls.Add(litSpace2); HyperLink hlGridViewForDropDown = new HyperLink(); hlGridViewForDropDown.Text = "Search"; hlGridViewForDropDown.NavigateUrl = "GridView.aspx?typename=" + prop.PropertyType.Name; plcForm.Controls.Add(hlGridViewForDropDown); CreateLineBreak(); } } } }
public void WhenValidatorIsNotEvaluatedBecauseWhenExpressionReturnsFalse() { RegularExpressionValidator validator = new RegularExpressionValidator("'ljwdf87cwbh'", "false", @"((\d{1,2}\.\d{1,3}\.\d{1,3}\.\d{1,3}))"); bool valid = validator.Validate(null, new ValidationErrors()); Assert.IsTrue(valid, "Validation should succeed when regex validator is not evaluated."); }
protected void Page_Load(object sender, EventArgs e) { SuperForm1 = new SuperForm(); SuperForm1.ID = "SuperForm1"; SuperForm1.Title = "Employee Form"; SuperForm1.DataSourceID = "SqlDataSource1"; SuperForm1.AutoGenerateRows = false; SuperForm1.AutoGenerateInsertButton = true; SuperForm1.AutoGenerateEditButton = true; SuperForm1.AutoGenerateDeleteButton = true; SuperForm1.DataKeyNames = new string[] { "EmployeeID" }; SuperForm1.AllowPaging = true; SuperForm1.DefaultMode = DetailsViewMode.Edit; CustomValidator field4Custom = new CustomValidator(); field4Custom.ID = "CustomValidator1"; field4Custom.ServerValidate += ValidateTitle; field4Custom.ErrorMessage = "Title needs to be 'Mr.', 'Ms.', 'Mrs.' or 'Dr.'"; field4Custom.Display = ValidatorDisplay.Dynamic; RangeValidator field5Custom = new RangeValidator(); field5Custom.ID = "RangeValidator1"; field5Custom.MinimumValue = "1900/1/1"; field5Custom.MaximumValue = "2039/12/31"; field5Custom.Type = ValidationDataType.Date; field5Custom.ErrorMessage = "*"; RegularExpressionValidator field6Custom = new RegularExpressionValidator(); field6Custom.ID = "RegularExpressionValidator1"; field6Custom.Display = ValidatorDisplay.Dynamic; field6Custom.ValidationExpression = "^(\\(?\\s*\\d{3}\\s*[\\)\\-\\.]?\\s*)?[1-9]\\d{2}\\s*[\\-\\.]\\s*\\d{4}$"; field6Custom.ErrorMessage = "Phone numbers must have this format (###) ###-####"; Obout.SuperForm.BoundField field1 = new Obout.SuperForm.BoundField(); field1.DataField = "EmployeeID"; field1.HeaderText = "Employee ID"; field1.ReadOnly = true; field1.InsertVisible = false; Obout.SuperForm.BoundField field2 = new Obout.SuperForm.BoundField(); field2.DataField = "FirstName"; field2.HeaderText = "First Name"; field2.Required = true; Obout.SuperForm.BoundField field3 = new Obout.SuperForm.BoundField(); field3.DataField = "LastName"; field3.HeaderText = "Last Name"; field3.Required = true; Obout.SuperForm.BoundField field4 = new Obout.SuperForm.BoundField(); field4.DataField = "TitleOfCourtesy"; field4.HeaderText = "Courtesy Title"; field4.Required = true; field4.Validators.Add(field4Custom); Obout.SuperForm.DateField field5 = new Obout.SuperForm.DateField(); field5.DataField = "BirthDate"; field5.HeaderText = "Birth Date"; field5.Required = true; field5.DataFormatString = "{0:MM/dd/yyyy}"; field5.ApplyFormatInEditMode = true; field5.Validators.Add(field5Custom); Obout.SuperForm.BoundField field6 = new Obout.SuperForm.BoundField(); field6.DataField = "HomePhone"; field6.HeaderText = "Home Phone"; field6.Required = true; field6.Validators.Add(field6Custom); SuperForm1.Fields.Add(field1); SuperForm1.Fields.Add(field2); SuperForm1.Fields.Add(field3); SuperForm1.Fields.Add(field4); SuperForm1.Fields.Add(field5); SuperForm1.Fields.Add(field6); SuperForm1Container.Controls.Add(SuperForm1); }
protected void Page_Load(object sender, EventArgs e) { List<Event> events = Event.GetAllEvents(); foreach (Event selectedEvent in events) { Panel pnlEvent = new Panel(); pnlEvent.ID = selectedEvent.ID.ToString(); pnlEvent.Attributes.Add("class", "panel"); CheckBox chkbxEventName = new CheckBox(); chkbxEventName.ID = "chkbx" + selectedEvent.Name; chkbxEventName.Text = selectedEvent.Name; pnlEvent.Controls.Add(chkbxEventName); for (int i = 0; i < selectedEvent.MaxTeamSize; i++) { TextBox txtbxTTID = new TextBox(); txtbxTTID.ID = "TTID" + (i + 1).ToString() + selectedEvent.ID; txtbxTTID.Attributes.Add("placeholder", "TTID " + (i + 1).ToString()); txtbxTTID.Attributes.Add("style", "display:none;"); pnlEvent.Controls.Add(txtbxTTID); RegularExpressionValidator rev = new RegularExpressionValidator(); rev.ControlToValidate = txtbxTTID.ClientID; rev.Attributes.Add("style", "display:none;"); rev.ValidationExpression = "\\d{4}"; rev.ErrorMessage = "*"; pnlEvent.Controls.Add(rev); } pnlEvents.Controls.Add(pnlEvent); } }