Implement the 'required' check box field validator
In the Web Forms for Marketers module, by default, the Check box field does not support the 'required' validation rule.
This topic outlines how you can make this field 'required' in the following ways:
-
Use the Check box field and mark it as required
-
Create a custom validator for the Check box field
This is only valid for web forms and does not support MVC forms.
Use the Check box field and mark it as required
To make the Check box field 'required' by using the field:
-
Add the Check box field to a web form.
-
Add one item to the list.
-
Mark this Check box as required.
-
Click Save.
Create a custom validator for the Check box field
To create a custom validator for the Check box field:
-
Create a class that is inherited from the
System.Web.UI.WebControls.BaseValidatorclass. See the code sample:RequestResponseclass CheckboxValidation : BaseValidator { protected CheckBox ctrToValidate; protected CheckBox CheckBoxToValidate { get { if (ctrToValidate == null) { ctrToValidate = base.FindControl(ControlToValidate) as CheckBox; } return ctrToValidate; } } protected override bool ControlPropertiesValid() { if (base.ControlToValidate == null || base.ControlToValidate.Length == 0) { throw new HttpException(string.Format("The ControlToValidate property of '{0}' cannot be blank.", this.ID)); } if (this.CheckBoxToValidate == null) { throw new HttpException(string.Format("The CheckBoxValidator can only validate controls of type CheckBox.")); } return true; } protected override bool EvaluateIsValid() { this.ErrorMessage = string.Format(this.ErrorMessage, "{0}", CheckBoxToValidate.Text); //Validate whether checkbox is checked return this.CheckBoxToValidate.Checked == true; } } -
In the content tree, navigate to the
sitecore/System/Modules/Web Forms for Marketers/Settings/Validationfolder and create an item by clicking the BaseValidator button.The item must be based on the BaseValidator template.
-
In the Message dialog, enter a name for the new item. Click OK.
-
In the right pane, in the Assembly and Class fields, enter the relevant values from your custom assembly.
-
In the Validator section, in the Error Message field, enter the following string:
The {0} check box must be checked. -
In the Text field, enter a relevant message. If this field is blank, its value is the same as the one in the Error Message field.
-
Duplicate the
/sitecore/System/Modules/Web Forms for Marketers/Settings/Field Types/Simple Types/checkboxitem and rename it to CheckBoxRequired.NoteIn the CheckBoxRequired item, do not select the Required check box.
-
In the
/sitecore/system/modules/web forms for marketers/settings/field types/simple types/CheckBoxRequireditem, in the Validation field, select your custom validator.
