Monday 10 April 2017

How To: Use Regular Expressions to Constrain Input in ASP.NET / Sharepoint

CompareValidator Datecpv = new CompareValidator();
Datecpv.ID = "Datecpv" ;
Datecpv.Text = "Date should not be greater than current date";
Datecpv.ControlToValidate = "";
Datecpv.Type = ValidationDataType.Date;
Datecpv.Operator = ValidationCompareOperator.LessThan;
Datecpv.ValueToCompare = DateTime.Today.ToShortDateString();

RegularExpressionValidator regDOB = new RegularExpressionValidator();
regDOB.ID = "regDOB";
regDOB.Text = "<br/>Please enter a valid Date of Birth dd/mm/yyyy.";
regDOB.ControlToValidate = "";
regDOB.ValidationExpression = @"^([0-9]{1,2})[/]+([0-9]{1,2})[/]+([0-9]{2}|[0-9]{4})$";                 regDOB.Attributes.Add("style", "font-weight: bold;color:red;");
newRow.Controls.Add(regDOB);

RegularExpressionValidator regCountry = new RegularExpressionValidator();                                       regCountry.ID = "reg_STD";
regCountry.Text = "Please enter a valid country code.";
regCountry.ControlToValidate = "";
regCountry.ValidationExpression = @"^\+[0-9]{1,2}$";
regCountry.Attributes.Add("style", "font-weight: bold;color:red;");
newRow.Controls.Add(regCountry);

RegularExpressionValidator regSTD = new RegularExpressionValidator();
regSTD.ID = "reg_STD";
regSTD.Text = "Please enter a valid STD code.";
regSTD.ControlToValidate = "";
regSTD.ValidationExpression = @"^[0-9]{1,6}$";
regSTD.Attributes.Add("style", "font-weight: bold;color:red;");
newRow.Controls.Add(regSTD);

RegularExpressionValidator regPhNumber = new RegularExpressionValidator();
regPhNumber.ID = "reg_PhNumber";
regPhNumber.Text = "Please enter a valid Phone number.";
regPhNumber.ControlToValidate = "";
regPhNumber.ValidationExpression = @"^[0-9]{1,12}$";
regPhNumber.Attributes.Add("style", "font-weight: bold;color:red;");
newRow.Controls.Add(regPhNumber);

No comments:

Post a Comment