Forms Support

The Checkbox component can be easily integrated with HTML5 form as well as KendoReact Form (or other third-party solutions).

The form enables you to validate checkbox values and prevent the submission of forms which are in an invalid state.

In addition to the exposed form support settings, the Checkbox provides the same properties and behaves in the same way as a native HTML input[type=checkbox] element.

Functionality and Features

Support for KendoReact Form and Setting Custom Behavior

The KendoReact Form component integrates with all KendoReact components.

You can display error messages and fully customize the behavior of the rendered component by using the additional properties of the Field component.

The following example demonstrates how to render a required custom checkbox a terms agreement.

import React from 'react';
import ReactDOM from 'react-dom';
import { Form, Field, FormElement, FieldWrapper } from '@progress/kendo-react-form';
import { Label, Hint, Error } from '@progress/kendo-react-labels';
import { Input, Checkbox } from '@progress/kendo-react-inputs';
import { Button } from '@progress/kendo-react-buttons';

const firstNameValidator = (value) => !value ?
    "First Name is required" :
    value.length < 7 ? "First Name should be at least 7 characters long." : "";

const lastNameValidator = (value) => !value ?
    "Last Name is required" :
    value.length < 7 ? "Last Name should be at least 7 characters long." : "";

const checkboxValidator = (value) => !value ?
    "Terms&Conditions checkbox is required" : "";

const FormInput = (fieldRenderProps) => {
    const { validationMessage, touched, label, id, valid, disabled, hint, type, optional, ...others } = fieldRenderProps;

    const showValidationMessage = touched && validationMessage;
    const showHint = !showValidationMessage && hint;
    const hindId = showHint ? `${id}_hint` : '';
    const errorId = showValidationMessage ? `${id}_error` : '';

    return (
        <FieldWrapper>
            <Label editorId={id} editorValid={valid} editorDisabled={disabled} optional={optional}>{label}</Label>
            <div className={'k-form-field-wrap'}>
                <Input
                    valid={valid}
                    type={type}
                    id={id}
                    disabled={disabled}
                    ariaDescribedBy={`${hindId} ${errorId}`}
                    {...others}
                />
                {
                    showHint &&
                    <Hint id={hindId}>{hint}</Hint>
                }
                {
                    showValidationMessage &&
                    <Error id={errorId}>{validationMessage}</Error>
                }
            </div>
        </FieldWrapper>
    );
};

const FormCheckbox = (fieldRenderProps) => {
    const { validationMessage, touched, id, valid, disabled, hint, optional, label, ...others } = fieldRenderProps;

    const showValidationMessage = touched && validationMessage;
    const showHint = !showValidationMessage && hint;
    const fullLabel = <span>{label}{optional ? <span className={'k-label-optional'}>(Optional)</span> : ''}</span>;
    const hindId = showHint ? `${id}_hint` : '';
    const errorId = showValidationMessage ? `${id}_error` : '';

    return (
        <FieldWrapper>
            <Checkbox
                ariaDescribedBy={`${hindId} ${errorId}`}
                label={fullLabel}
                valid={valid}
                id={id}
                disabled={disabled}
                {...others}
            />
            {
                showHint &&
                <Hint id={hindId}>{hint}</Hint>
            }
            {
                showValidationMessage &&
                <Error id={errorId}>{validationMessage}</Error>
            }
        </FieldWrapper>
    );
};

const App = () => {
    const handleSubmit = (dataItem) => alert(JSON.stringify(dataItem, null, 2));
    return (
        <Form
            onSubmit={handleSubmit}
            render={(formRenderProps) => (
                <FormElement style={{ width: 400 }}>
                    <fieldset className={'k-form-fieldset'}>
                        <legend className={'k-form-legend'}>User Details</legend>
                        <Field
                            id={'firstName'}
                            name={'firstName'}
                            label={'First Name'}
                            component={FormInput}
                            validator={firstNameValidator}
                        />
                        <Field
                            id={'lastName'}
                            name={'lastName'}
                            label={'Last Name'}
                            component={FormInput}
                            validator={lastNameValidator}
                        />
                        <Field
                            id={'terms'}
                            name={'terms'}
                            label={'I agree with terms and conditions'}
                            hint={'Hint: By checking this, you agree to our Terms&Conditions'}
                            component={FormCheckbox}
                            validator={checkboxValidator}
                        />
                        <div className="k-form-buttons">
                            <Button
                                primary={true}
                                type={'submit'}
                                disabled={!formRenderProps.allowSubmit}
                            >
                                Submit
                        </Button>
                            <Button onClick={formRenderProps.onFormReset}>
                                Clear
                        </Button>
                        </div>
                    </fieldset>
                </FormElement>
            )}
        />
    );
}

ReactDOM.render(
    <App />,
    document.querySelector('my-app')
);

Setting Validation Requirements

The Checkbox supports props for setting basic validation. For example, the required property which prevents form submission when Checkbox is not checked.

import * as React from 'react';
import * as ReactDOM from 'react-dom';

import { Input, Checkbox } from '@progress/kendo-react-inputs';

class App extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            success: false
        };
    }
    render() {
        return (
            <div className="row example-wrapper">
                <div className="col-xs-12 col-sm-8 offset-sm-2 example-col">
                    <form className="k-form" onSubmit={this.handleSubmit}>
                        <fieldset className="k-form-fieldset">
                            <legend className="k-form-legend">Create new account:</legend>
                            <div className="mb-3">
                                <Input
                                    name="username"
                                    style={{ width: "100%" }}
                                    label="First Name"
                                    pattern={"[A-Za-z]+"}
                                    minLength={2}
                                    required={true}
                                />
                            </div>
                            <div className="mb-3">
                                <Input
                                    name="password"
                                    type="password"
                                    style={{ width: '100%' }}
                                    label="Password"
                                    required={true}
                                    minLength={6}
                                    maxLength={18}
                                />
                            </div>
                            <div className="mb-3">
                                <Checkbox
                                    id="ch"
                                    name="checkbox"
                                    required={true}
                                >
                                    <label className="k-checkbox-label" style={{ 'display': 'inline-block' }} for="ch">
                                        By clicking <a href="#">Sign Up</a>, you agree to our <a href="#">Terms and Conditions</a>.
                                            </label>
                                </Checkbox>
                            </div>
                        </fieldset>
                        <input type="submit" className="k-button k-primary" value="Sign up" />
                    </form>
                </div>
                {this.state.success && (
                    <div
                        className="alert alert-success"
                        style={{ position: 'absolute' }}
                    >
                        Form submitted!
                    </div>)}
            </div>
        );
    }

    handleSubmit = (event) => {
        event.preventDefault();
        this.setState({ success: true });
        setTimeout(() => { this.setState({ success: false }); }, 3000);
    }
}

ReactDOM.render(
    <App />,
    document.querySelector('my-app')
);

Setting Custom Validation Messages

You can implement custom error messages which will be displayed when the Checkbox is in an invalid state and the user tries to submit the form. To render a custom validation message, set the validationMessage prop.

import * as React from 'react';
import * as ReactDOM from 'react-dom';

import { Input, Checkbox } from '@progress/kendo-react-inputs';

class App extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            success: false
        };
    }
    render() {
        const usernameValidationMessage = "Your username should contain only letters";
        const passwordValidationMessage = "Please enter password between 6 and 16 characters";
        const checkboxTermsAndConditionsMessage = "Please indicate that you accept the Terms and Conditions";
        const checkboxsignUpToNewsletterMessage = "Please sign up to the Newsletter";

        return (
            <div className="row example-wrapper">
                <div className="col-xs-12 col-sm-8 offset-sm-2 example-col">
                    <form className="k-form" onSubmit={this.handleSubmit}>
                        <fieldset className="k-form-fieldset">
                            <legend className="k-form-legend">Create new account:</legend>
                            <div className="mb-3">
                                <Input
                                    name="username"
                                    style={{ width: "100%" }}
                                    label="First Name"
                                    pattern={"[A-Za-z]+"}
                                    minLength={2}
                                    required={true}
                                    validationMessage={usernameValidationMessage}
                                />
                            </div>
                            <div className="mb-3">
                                <Input
                                    name="password"
                                    type="password"
                                    style={{ width: '100%' }}
                                    label="Password"
                                    required={true}
                                    minLength={6}
                                    maxLength={18}
                                    validationMessage={passwordValidationMessage}
                                />
                            </div>
                            <div className="mb-3">
                                <Input
                                    name="confirmPassword"
                                    type="password"
                                    style={{ width: '100%' }}
                                    label="Confirm Password"
                                    required={true}
                                    minLength={6}
                                    maxLength={18}
                                    validationMessage={passwordValidationMessage}
                                />
                            </div>
                            <div className="mb-3">
                                <Input
                                    name="email"
                                    type="email"
                                    style={{ width: '100%' }}
                                    label="Email address"
                                    required={true}
                                />
                            </div>
                            <div className="mb-3">
                                <Checkbox
                                    id="ch1"
                                    name="checkbox"
                                    required={true}
                                    validationMessage={checkboxTermsAndConditionsMessage}
                                >
                                    <label className="k-checkbox-label" style={{ 'display': 'inline-block' }} for="ch1">
                                        By clicking <a href="#">Sign Up</a>, you agree to our <a href="#">Terms and Conditions</a>.
                                            </label>
                                </Checkbox>
                            </div>
                            <div className="mb-3">
                                <Checkbox
                                    id="ch2"
                                    name="checkbox2"
                                    required={true}
                                    label={"Sign-up to our newsletter!"}
                                    validationMessage={checkboxsignUpToNewsletterMessage}
                                />
                            </div>
                        </fieldset>
                        <input type="submit" className="k-button k-primary" value="Sign up" />
                    </form>
                </div>
                {this.state.success && (
                    <div
                        className="alert alert-success"
                        style={{ position: 'absolute' }}
                    >
                        Form submitted!
                    </div>)}
            </div>
        );
    }

    handleSubmit = (event) => {
        event.preventDefault();
        this.setState({ success: true });
        setTimeout(() => { this.setState({ success: false }); }, 3000);
    }
}

ReactDOM.render(
    <App />,
    document.querySelector('my-app')
);

Disabling the Validation Styling

By default, to achieve a visual representation of its invalid state, the Checkbox applies the k-state-invalid class name to the wrapping component. To disable the utilization of k-state-invalid, set the validityStyles property to false.

import * as React from 'react';
import * as ReactDOM from 'react-dom';

import { Input, Checkbox } from '@progress/kendo-react-inputs';

class App extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            password: '',
            confirmPassword: '',
            success: false
        };
    }
    render() {
        const usernameValidationMessage = "Your username should contain only letters";
        const passwordValidationMessage = "Please enter password between 6 and 16 characters";
        const confirmPasswordValidationMessage = "Passwords does not match";

        return (
            <div className="row example-wrapper">
                <div className="col-xs-12 col-sm-6 offset-sm-3 example-col">
                    <form className="k-form" onSubmit={this.handleSubmit}>
                        <fieldset className="k-form-fieldset">
                            <legend className="k-form-legend">Create new account:</legend>
                            <div className="mb-3">
                                <Input
                                    validityStyles={false}
                                    name="username"
                                    style={{ width: "100%" }}
                                    label="First Name"
                                    pattern={"[A-Za-z]+"}
                                    minLength={2}
                                    required={true}
                                    validationMessage={usernameValidationMessage}
                                />
                            </div>
                            <div className="mb-3">
                                <Input
                                    validityStyles={false}
                                    value={this.state.password}
                                    onChange={this.handleChange}
                                    name="password"
                                    type="password"
                                    style={{ width: '100%' }}
                                    label="Password"
                                    required={true}
                                    minLength={6}
                                    maxLength={18}
                                    validationMessage={passwordValidationMessage}
                                />
                            </div>
                            <div className="mb-3">
                                <Input
                                    validityStyles={false}
                                    value={this.state.confirmPassword}
                                    onChange={this.handleChange}
                                    name="confirmPassword"
                                    type="password"
                                    style={{ width: '100%' }}
                                    label="Confirm Password"
                                    valid={this.state.password && this.state.password === this.state.confirmPassword}
                                    minLength={6}
                                    maxLength={18}
                                    validationMessage={confirmPasswordValidationMessage}
                                />
                            </div>
                            <div className="mb-3">
                                <Input
                                    validityStyles={false}
                                    name="email"
                                    type="email"
                                    style={{ width: '100%' }}
                                    label="Email address"
                                    required={true}
                                />
                            </div>
                            <div className="mb-3">
                                <Checkbox
                                    validityStyles={false}
                                    id="ch3"
                                    name="checkbox"
                                    required={true}
                                    label={"Sign-up to our newsletter!"}
                                />
                            </div>
                        </fieldset>
                        <input type="submit" className="k-button k-primary" value="Search" />
                    </form>
                </div>
                {this.state.success && (
                    <div
                        className="alert alert-success"
                        style={{ position: 'absolute' }}
                    >
                        Form submitted!
                    </div>)}
            </div>
        );
    }

    handleChange = (event) => {
        this.setState({
            [event.target.name]: event.target.value
        });
    }

    handleSubmit = (event) => {
        event.preventDefault();
        this.setState({ success: true });
        setTimeout(() => { this.setState({ success: false }); }, 3000);
    }
}

ReactDOM.render(
    <App />,
    document.querySelector('my-app')
);