Eliah John
Eliah John

Reputation: 77

.NET validate dynamically created fields

I'm working on a page where I have to dynamically add multiple fields. I've basically completed the job but I'm being held back by the validation.
The problem is that the form fields need specific regex validation which worked well when there was only a single input. Now, when fields are dynamically created by javascript, it only validates the first field.

I've googled around but haven't found anything and for now my only idea is to pass regex value from the settings file to javascript and validate it on the user side but I won't be able to use Page.IsValid() then.

So my question is - is it possible to add server side validation to fields dynamically created by javascript, and how?

Thank you!

Upvotes: 0

Views: 2063

Answers (2)

Frank Baker
Frank Baker

Reputation: 146

Short answer is – it is probably possible but it’s very difficult and solution would be very brittle and require a lot of maintenance.

In theory you could do this if you can figure out JS code generated by ASP.NET when regular expression validators are used and then reverse engineer it. Main issue here is that new fields are created on client and not on the server side.

If you can update your page so that new textboxes are created dynamically on the server side then all you have to do is create new text box and new validator in OnInit method and this would work.

Here is how it could look like.

protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        //set the appropriate conditions for your solution
        if (true)
        {
            //create text box
            TextBox txtNewField = new TextBox();
            txtNewField.ID = "txtNewField";

            //create and initialize validator
            RegularExpressionValidator regexR1 = new RegularExpressionValidator();

            regexR1.ValidationExpression = "set the regex here";
            regexR1.ControlToValidate = txtNewField.ID;
            regexR1.ErrorMessage = "you are doing something wrong";

            //add both of these to page wehre needed. 
            //I assume there is a panel control where you are adding these 
            //but you can customize it more
            pnlFields.Controls.Add(txtNewField);
            pnlFields.Controls.Add(regexR1);
        }
    }

Upvotes: 1

Akshay Joy
Akshay Joy

Reputation: 1765

If you want Server Side validation and Client side valdiation, then you need to Create the Input type="text" as runat ="server"

Example:-

<input type="text" class="alphanum" id="txtName" name="txtName" runat="server" />

Use Jquery to Validate using Regex

$("input.alphanum").bind("keyup", function(e) {
    this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
});

Upvotes: 0

Related Questions