Forms Support

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

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

In addition to the exposed form support settings, the Switch 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 switch.

import React from 'react';
import ReactDOM from 'react-dom';
import { Form, Field } from '@progress/kendo-react-form';
import { Input, Switch } 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 MyCustomSwitch = (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(
        () => {
            // onChange callback expects argument with 'value' property
            onChange({value: !value});
        },
        [onChange, value]
    );

    return (
        <div onFocus={onFocus} onBlur={onBlur}>
            <Switch
                onChange={onValueChange}
                checked={value}
                id={others.id}
            />
            {
                // Display an error message after the "visited" or "touched" field is set to true.
                (visited && 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={'keepMeSignedIn'}
                                id={'termsinput'}
                                component={MyCustomSwitch}
                                validator={requiredValidator}
                            />
                            <span style={{ fontSize: 12 }}>Keep me signed in</span>
                        </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 Switch supports props for setting basic validation requirements. For example, the required property which enables the successful form submission.

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

import { Input, Switch } 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">
                                        <Switch
                                            id="switch1"
                                            name="switch"
                                            style={{ width: '100%' }}
                                            required={true}
                                        />
                                        <span style={{ marginLeft: 10, fontSize: 12 }}>Keep me signed in</span>
                                    </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 if the Switch is not turned on 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, Switch } 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 switchCustomMesssage = "Please turn the automatic sign in";

        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">
                                        <Switch
                                            id="switch1"
                                            name="switch"
                                            style={{ width: '100%' }}
                                            required={true}
                                            validationMessage={switchCustomMesssage}
                                        />
                                        <span style={{ marginLeft: 10, fontSize: 12 }}>Keep me signed in</span>
                                    </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')
);
 /