vendredi 15 juillet 2022

Validate a dynamically generated CheckBox

I'm generating an asp:CheckBox dynamically and I need to validate that it is checked with a CustomValidator().

private void AddCheckBox(HtmlGenericControl newDiv, AdditionalFields field)
    {
        var additionalFieldDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
        additionalFieldDiv.Attributes.Add("class", "additional-field-row");


        var additionalLabel = new RadLabel();
        additionalLabel.Text = field.Label;
        additionalLabel.ID = "AdditionalLabel" + field.ControlId;
        additionalLabel.CssClass += "title ";
        additionalLabel.Width = new Unit(field.LabelWidth ?? 175);
        if (field.Required??false) additionalLabel.CssClass += "additional-field-required";

        var additionalField = new System.Web.UI.WebControls.CheckBox();
        additionalField.ID = "AdditionalField" + field.ControlId;
        
        additionalField.CssClass += "additional-field-checkbox";
        additionalField.Width = new Unit(field.Width ?? 200);


        var customValidator = new CustomValidator();
        customValidator.ID = "CustomValidator" + field.ControlId;
        //customValidator.ClientValidationFunction = "CheckBoxValidation(AdditionalField"+ field.ControlId +")";
        customValidator.ControlToValidate = "AdditionalField" + field.ControlId;
        customValidator.ErrorMessage = string.IsNullOrEmpty(field.ErrorMessage) ? field.Label + " required" : field.ErrorMessage;
        customValidator.CssClass += "additional-fields-validator";
        customValidator.Display = ValidatorDisplay.Dynamic;
        customValidator.ValidationGroup = "valGroup";
        customValidator.EnableClientScript = true;

        newDiv.Controls.Add(additionalFieldDiv);
        additionalFieldDiv.Controls.Add(additionalLabel);
        additionalFieldDiv.Controls.Add(additionalField);

        if (field.Required ?? false)
        {
            additionalFieldDiv.Controls.Add(customValidator);
        }

    }

I get an error if I try to use customValidator.ControlToValidate = "AdditionalField" + field.ControlId;

Control 'AdditionalField9' referenced by the ControlToValidate property of 'CustomValidator9' cannot be validated.

I have several other controls on the page that are in the validation group "valGroup" and I like the CheckBox validated client side. If I can't use the ControlToValidate property do I need to use JavaScript, and if so how do I pass the ID of the CheckBox to validate?

 <script type = "text/javascript">
    function ValidateCheckBox(sender, args) {
        if (document.getElementById("<%=AdditionalField9.ClientID %>").checked == true) {
            args.IsValid = true;
        } else {
            args.IsValid = false;
        }
    }
</script>

Hope you can help




Aucun commentaire:

Enregistrer un commentaire