Sander
Sander

Reputation: 13421

adding conditional requiredFieldValidators to dynamically created form in c# asp.net

Ok,

i have a fully rendered dynamic form ( i do not know the content of the form, it is provided to my via a webservice )

i used asp.net RequiredFieldValidator for validation, because i read in this article that we could dynamically switch validators on and off depending if the field is visible or not with the ValidatorEnable(val, enabled) function.

though now that i got the form rendered, i'm running into a bit of trouble with this javascript, as i don't want to put it in the aspx file itself, (don't have a control there anyway since the form is build up in codebehind from the webservice data...)

so i took a look at the clientId and it turns out the validator's client ID is the id of the span it renders to.

so i tried running this in firebug to test if i could enable / disable one of those validators, but that seems not to be possible, a jQuery span element does not have a property to enable it.

ValidatorEnable($("#ContentPlaceHolderDefault_MasterWithNavContent_Poll_4_reqAnswer_373ac8b7_8da9_467b_b9b4_d586e45a7504"), false);

and the html that goes with this

<div class="question-container question-odd" id="ContentPlaceHolderDefault_MasterWithNavContent_Poll_4_question-373ac8b7-8da9-467b-b9b4-d586e45a7504">
    <div class="question-meta">
        <h3 class="validation-label">Which club have you visited?</h3>
        <span style="display: block; margin-bottom: 10px; margin-top: 5px;" class="error validation" id="ContentPlaceHolderDefault_MasterWithNavContent_Poll_4_reqAnswer_373ac8b7_8da9_467b_b9b4_d586e45a7504">Please fill out this field.</span>
    </div>
    <input type="text" class="answer-container text" id="ContentPlaceHolderDefault_MasterWithNavContent_Poll_4_answer_373ac8b7_8da9_467b_b9b4_d586e45a7504" name="ctl00$ctl00$ctl00$ContentPlaceHolderDefault$MasterWithNavContent$Poll_4$answer_373ac8b7_8da9_467b_b9b4_d586e45a7504">
</div>

Does someone know where i'm going wrong here? maybe I'm to quick to jump from the serverside ClientId to the <span> which the RFV renders into? but they seem exactly the same. hope someone can point me in the good direction!

Upvotes: 2

Views: 1291

Answers (2)

Billy Jo
Billy Jo

Reputation: 1332

Perhaps a more appropriate way to do this would be

ValidatorEnable($("<%= reqAnswer.ClientID %>")[0], false);

Using <%= reqAnswer.ClientID %> avoids having to guess at or hard-code the client-side ID of the validator. Adding [0] after the jQuery $() gets the actual validator DOM element instead of the jQuery wrapper.

Source for [0]

Upvotes: 0

M4N
M4N

Reputation: 96551

Maybe a better approach would be to loop through the client-side array of validators (Page_Validators) and find the validator which you want to disable.

See also this MSDN page and this codeproject article for more information.

Upvotes: 1

Related Questions