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 } from '@progress/kendo-react-form';
import { Input, Checkbox } from '@progress/kendo-react-inputs';

const emailRegex = new RegExp(/\S+@\S+\.\S+/);
const emailValidator = (value) => (emailRegex.test(value) ? "" : "Please enter a valid email.");
const EmailInput = (fieldRenderProps) => {
  const { validationMessage, visited, ...others } = fieldRenderProps;
  return (
    <div>
      <Input {...others} />
      {
        visited && validationMessage &&
          (<div className={"k-required"}>{validationMessage}</div>)
      }
    </div>
  );
};

const MyCustomCheckbox = (fieldRenderProps) => {
    const {
        // The meta props of the Field.
        validationMessage, touched, visited, modified, valid,
        // The input props of the Field.
        value, onChange, onFocus, onBlur,
        // The custom props that you passed to the Field.
        ...others
    } = fieldRenderProps;

    const onValueChange = React.useCallback(
        (event) => {
            onChange({value: event.value});
        },
        [onChange]
    );

    return (
        <div onFocus={onFocus} onBlur={onBlur}>
            <Checkbox
                onChange={onValueChange}
                checked={value}
                id={others.id}
                label={others.label}
            />
            {
                // Display an error message after the "visited" or "touched" field is set to true.
                (touched && validationMessage) && (
                    <div className={'k-required'}>
                        {validationMessage}
                    </div>
                )
            }
        </div>
    );
};

const requiredValidator = (value) => value ? '' : 'This field is required.';

const App = () => {
    const handleSubmit = (dataItem) => alert(JSON.stringify(dataItem, null, 2));
    return (
        <Form
            onSubmit={handleSubmit}
            render={(formRenderProps) => (
                <form onSubmit={formRenderProps.onSubmit} className={'k-form'}>
                    <fieldset>
                        <legend>Please fill in the fields:</legend>
                        <div className="mb-3">
                            <Field name={'firstName'} component={Input} label={'First name'} />
                        </div>

                        <div className="mb-3">
                            <Field name={'lastName'} component={Input} label={'Last name'} />
                        </div>

                        <div className="mb-3">
                            <Field name={"email"} type={"email"} component={EmailInput} label={"Email"} validator={emailValidator} />
                        </div>
                        <div className="mb-3">
                            <Field
                                name={'termsAccepted'}
                                label={'I Agree with terms & conditions'}
                                id={'termsinput'}
                                component={MyCustomCheckbox}
                                validator={requiredValidator}
                            />
                        </div>
                    </fieldset>
                    <button
                        type={'submit'}
                        className="k-button"
                        disabled={!formRenderProps.allowSubmit}
                    >
                        Submit
                    </button>
                </form>
            )}
        />
    );
};
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-6 offset-sm-3 example-col">
                    <div className="card">
                        <div className="card-block">
                            <form className="k-form" onSubmit={this.handleSubmit}>
                                <fieldset>
                                    <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"
                                            style={{ width: '100%' }}
                                            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>
                    </div>
                </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-6 offset-sm-3 example-col">
                    <div className="card">
                        <div className="card-block">
                            <form className="k-form" onSubmit={this.handleSubmit}>
                                <fieldset>
                                    <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"
                                            style={{ width: '100%' }}
                                            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"
                                            style={{ width: '100%' }}
                                            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>
                    </div>
                </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">
                    <div className="card">
                        <div className="card-block">
                            <form className="k-form" onSubmit={this.handleSubmit}>
                                <fieldset>
                                    <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"
                                            style={{ width: '100%' }}
                                            required={true}
                                            label={"Sign-up to our newsletter!"}
                                        />
                                    </div>
                                </fieldset>
                                <input type="submit" className="k-button k-primary" value="Search" />
                            </form>
                        </div>
                    </div>
                </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')
);