0

I am trying to validate a textbox using RequiredFieldValidator and display error message in ValidationSummary through code behind, but I am not able to do that. My code goes here

        if (txtUsrName.Text.Length == 0 || txtUsrAge.Text.Length == 0)
        {
            RequiredFieldValidator req = new RequiredFieldValidator();
            req.ID = "Required";
            req.ControlToValidate = txtUsrName.ID;                                
            req.IsValid = false;
            req.Visible = true;
            req.Enabled = true;                               
            req.ValidationGroup = "ValidationGroup";
            req.ErrorMessage = "Thease are required fields";
            req.InitialValue = "";
            req.Text = "*";

            ValidationSummary valsum = new ValidationSummary();
            ValidationSummaryDisplayMode mode = new ValidationSummaryDisplayMode();
            valsum.ID = "validatesummury";                
            valsum.HeaderText = "please correct the following errors";                
            valsum.DisplayMode = mode;
            valsum.ShowSummary = true;
            valsum.ValidationGroup = "ValidationGroup";
            valsum.Visible = true;                
        }

Please help me with this

Liath
  • 9,913
  • 9
  • 51
  • 81
venkatesh
  • 11
  • 1
  • 5

2 Answers2

2

you can use Page.Validate() OR Page.Validate("YOUR_VALIDATION_GROUP") and then check Page.IsValid to check if all validators are valid, and to special validator also you can use YOUR_RequiredFieldValidator.IsValid 'YOUR_RequiredFieldValidator' is one attached to your textbox control

Amir Sherafatian
  • 2,083
  • 2
  • 20
  • 32
0

Here is a similar question that may provide insight for you: Unobtrusive Validation in Webforms using Data Annotations. Data Annotations provide ways to check the length, minimum/maximum value, etc of class properties.

FrankO
  • 2,522
  • 6
  • 24
  • 34