Input · Form

Form

Form

  • Rerender on demand, avoids unnecessary full-volume rendering, higher performance
  • Easy to use, simple structure, avoids unnecessary hierarchical nesting
  • Perfect accessibility support
  • FormState / FieldState can also be easily obtained from outside the Form Provides an external method to operate inside the form: formApi / fieldApi
  • Support for encapsulating custom components into form controls, and you can quickly access your team's components through the extension mechanism provided by Form (through withField)
  • Support Form level / Field level assignment, verification (synchronous / asynchronous)

Field

Semi encapsulates all form field component (Input、Select、Checkbox、DatePicker etc.) with withField once.
Taking over their data flow (value & onChange)
When in use, you need to use the components whose names start with Form (note: only these components have data synchronization). They are named exports and are not mounted under Form.

Supported Field Component

  • Fields: FormInput, FormInputNumber, FormTextArea, FormSelect, FormCheckbox, FormCheckboxGroup, FormRadio, FormRadioGroup, FormSwitch, FormDatePicker, FormTimePicker, FormSlider, FormTreeSelect, FormCascader, FormRating, FormAutoComplete, FormUpload, FormPinCode, FormTagInput
  • Other parts: ArrayField, and Form.InputGroup, Form.Label, Form.ErrorMessage, Form.Section, Form.Slot mounted under Form
// A field takes over its data flow when used inside <Form>
import { Form, FormInput, FormSelect, FormCheckbox, FormCheckboxGroup, FormRadio, FormRadioGroup, FormSwitch, FormDatePicker, FormTimePicker, FormInputNumber, FormTextArea, FormSlider, FormTreeSelect, FormCascader, FormRating, FormUpload, FormTagInput } from '@fibrous/semi-ui-solid';
// Dynamic forms and hooks
import { ArrayField, useFormApi, useFormState, useFieldApi, useFieldState, withField } from '@fibrous/semi-ui-solid';
// A plain Input is left untouched by the Form
import { Input } from '@fibrous/semi-ui-solid';

The Field level component provided by Form, its value (or other properties specified by valueKey) and onChange (or other callbacks specified by onKeyChangeFnName) are taken over by Form, so

Demos

Various ways to declare form

Semi Form supports multiple writing at the same time.

Basic Usage

Use the fields whose names start with Form, such as FormInput and FormSelect, add the field property to each of them, and place them inside the Form. You can also set label properties for each field, by default is the same as field

label can be passed in a string or JSX directly, or declared in the form of an object, configure text, extra, required, optional, align, width and other attributes to deal with more complex scenarios. Both text and extra can be JSX (the help icon in the example below)

Code
import { IconHelpCircle } from '@fibrous/semi-icons-solid';
import { Form, FormInput, FormSelect, Tooltip } from '@fibrous/semi-ui-solid';

export default function FormDemo() {
    return (
        <Form layout="horizontal" onValueChange={(values) => console.log(values)}>
            <FormInput field="UserName" label="用户名" style={{ width: '80px' }} />
            <FormInput
                field="Password"
                label={{
                    text: '密码',
                    extra: (
                        <Tooltip content="详情">
                            <IconHelpCircle aria-label="帮助" style={{ color: 'var(--semi-color-text-2)' }} />
                        </Tooltip>
                    ),
                }}
                style={{ width: '176px' }}
            />
            <FormSelect field="Role" label={{ text: '角色', optional: true }} style={{ width: '176px' }}>
                <FormSelect.Option value="admin">管理员</FormSelect.Option>
                <FormSelect.Option value="user">普通用户</FormSelect.Option>
                <FormSelect.Option value="guest">访客</FormSelect.Option>
            </FormSelect>
        </Form>
    );
}

Other declaration methods

When you need to get formState, formApi, values, etc. directly inside the Form structure, you can use the following writing

The render, the children function and component receive the same argument: { formState, values, formApi }. Each is called once, and formState and values in the argument follow the form; read them in the returned JSX (such as form.values.name) instead of destructuring them at the top of the function, which would only give the initial values.

Via the render property

That is, render props

{"values":{},"errors":{},"touched":{}}
Code
import { Form, FormInput, FormSelect } from '@fibrous/semi-ui-solid';

export default function FormDemo() {
    return (
        <Form
            render={(form) => (
                <>
                    <FormSelect field="Role" label="角色" style={{ width: '176px' }}>
                        <FormSelect.Option value="admin">管理员</FormSelect.Option>
                        <FormSelect.Option value="user">普通用户</FormSelect.Option>
                        <FormSelect.Option value="guest">访客</FormSelect.Option>
                    </FormSelect>
                    <FormInput field="UserName" label="用户名" style={{ width: '80px' }} />
                    <FormInput field="Password" label="密码" style={{ width: '176px' }} />
                    <code style={{ 'margin-top': '24px' }}>{JSON.stringify(form.formState)}</code>
                </>
            )}
            layout="horizontal"
            onValueChange={(values) => console.log(values)}
        />
    );
}

Via child render function

The children of Form is a function that returns all the fields. The function must declare a parameter, a function without parameters is treated as plain children

{"values":{},"errors":{},"touched":{}}
Code
import { Form, FormInput, FormSelect } from '@fibrous/semi-ui-solid';

export default function FormDemo() {
    return (
        <Form layout="horizontal" onValueChange={(values) => console.log(values)}>
            {(form) => (
                <>
                    <FormSelect field="Role" label="角色" style={{ width: '176px' }}>
                        <FormSelect.Option value="admin">管理员</FormSelect.Option>
                        <FormSelect.Option value="user">普通用户</FormSelect.Option>
                        <FormSelect.Option value="guest">访客</FormSelect.Option>
                    </FormSelect>
                    <FormInput field="UserName" label="用户名" style={{ width: '80px' }} />
                    <FormInput field="Password" label="密码" style={{ width: '176px' }} />
                    <code style={{ 'margin-top': '24px' }}>{JSON.stringify(form.formState)}</code>
                </>
            )}
        </Form>
    );
}

Via the component property

Pass the whole inner structure as a component through the component property. formState, values and formApi are its props

{"values":{},"errors":{},"touched":{}}
Code
import { Form, FormInput, type FormRenderProps } from '@fibrous/semi-ui-solid';

function Fields(props: FormRenderProps) {
    return (
        <>
            <FormInput field="Role" style={{ width: '176px' }} />
            <FormInput field="UserName" style={{ width: '80px' }} />
            <FormInput field="Password" style={{ width: '176px' }} />
            <code style={{ 'margin-top': '24px' }}>{JSON.stringify(props.formState)}</code>
        </>
    );
}

export default function FormDemo() {
    return <Form component={Fields} layout="horizontal" onValueChange={(values) => console.log(values)} />;
}

All supported field components

基本信息
没有找到合适的业务线?

abc

ulikeCam

已选择文件
vigo.png130KB
resso.jpeg222KB
douyin.jpeg222KB
资源详情
admin
user
guest
root
0100
我已阅读并清楚相关规定(Checkbox)
Code
import { IconUpload } from '@fibrous/semi-icons-solid';
import { Button, Col, Form, FormCascader, FormCheckbox, FormCheckboxGroup, FormDatePicker, FormInput, FormInputNumber, FormRadio, FormRadioGroup, FormRating, FormSelect, FormSlider, FormSwitch, FormTagInput, FormTextArea, FormTimePicker, FormTreeSelect, FormUpload, Row, Space } from '@fibrous/semi-ui-solid';

const today = new Date(2024, 4, 6, 12);

const initValues = {
    name: 'semi',
    business: ['ulikeCam'],
    role: 'ued',
    switch: true,
    files: [
        {
            uid: '1',
            name: 'vigo.png',
            status: 'success',
            size: '130KB',
            preview: true,
            url: '/assets/placeholder/avatar-d.svg',
        },
        {
            uid: '2',
            name: 'resso.jpeg',
            status: 'validateFail',
            size: '222KB',
            percent: 50,
            preview: true,
            fileInstance: new File([new ArrayBuffer(2048)], 'resso.jpeg', { type: 'image/jpeg' }),
            url: '/assets/placeholder/avatar-b.svg',
        },
        {
            uid: '3',
            name: 'douyin.jpeg',
            status: 'uploading',
            size: '222KB',
            percent: 50,
            preview: true,
            fileInstance: new File([new ArrayBuffer(2048)], 'dy.jpeg', { type: 'image/jpeg' }),
            url: '/assets/placeholder/avatar-a.svg',
        },
    ],
};

const treeData = [
    {
        label: '亚洲',
        value: 'Asia',
        key: '0',
        children: [
            {
                label: '中国',
                value: 'China',
                key: '0-0',
                children: [
                    {
                        label: '北京',
                        value: 'Beijing',
                        key: '0-0-0',
                    },
                    {
                        label: '上海',
                        value: 'Shanghai',
                        key: '0-0-1',
                    },
                ],
            },
        ],
    },
    {
        label: '北美洲',
        value: 'North America',
        key: '1',
    },
];

const style = { width: '90%' };

export default function FormDemo() {
    return (
        <Form initValues={initValues} style={{ padding: '10px', width: '100%' }} onValueChange={(v) => console.log(v)}>
            <Form.Section text="基本信息">
                <Row>
                    <Col span={12}>
                        <FormInput field="name" label="名称(Input)" initValue="mikeya" style={style} trigger="blur" />
                    </Col>
                    <Col span={12}>
                        <FormDatePicker field="date" label="日期(DatePicker)" style={style} initValue={today} placeholder="请选择生效日期" />
                    </Col>
                </Row>
                <Row>
                    <Col span={12}>
                        <FormSelect field="role" style={style} label="角色(Select)" placeholder="请选择你的角色">
                            <FormSelect.Option value="operate">运营</FormSelect.Option>
                            <FormSelect.Option value="rd">开发</FormSelect.Option>
                            <FormSelect.Option value="pm">产品</FormSelect.Option>
                            <FormSelect.Option value="ued">设计</FormSelect.Option>
                        </FormSelect>
                    </Col>
                    <Col span={12}>
                        <FormSelect field="business" multiple style={style} placeholder="请选择业务线" label="业务线(多选Select)" extraText={<div style={{ color: 'var(--semi-blue-5)', 'font-size': '14px', 'user-select': 'none', cursor: 'pointer' }}>没有找到合适的业务线?</div>}>
                            <FormSelect.Option value="abc">Semi</FormSelect.Option>
                            <FormSelect.Option value="ulikeCam">轻颜相机</FormSelect.Option>
                            <FormSelect.Option value="toutiao">今日头条</FormSelect.Option>
                        </FormSelect>
                    </Col>
                </Row>
                <Row>
                    <Col span={12}>
                        <FormCascader placeholder="请选择所在地区" treeData={treeData} field="area" label="地区(Cascader)" style={style} />
                    </Col>
                    <Col span={12}>
                        <FormTreeSelect field="tree" style={style} label="节点(TreeSelect)" placeholder="请选择服务节点" treeData={treeData} filterTreeNode />
                    </Col>
                </Row>
                <Row>
                    <Col span={12}>
                        <FormTagInput field="product" label="产品(TagInput)" initValue={['abc', 'ulikeCam']} placeholder="请输入产品" style={style} />
                    </Col>
                </Row>
                <Row>
                    <Col span={24}>
                        <FormUpload field="files" label="证明文件(Upload)" action="//semi.design/api/upload">
                            <Button icon={<IconUpload />} theme="light">
                                点击上传
                            </Button>
                        </FormUpload>
                    </Col>
                </Row>
            </Form.Section>
            <Form.Section text="资源详情">
                <Row>
                    <Col span={12}>
                        <FormTextArea style={{ ...style, height: '120px' }} field="description" label="申请理由(TextArea)" placeholder="请填写申请资源理由" />
                    </Col>
                    <Col span={12}>
                        <FormCheckboxGroup field="type" direction="horizontal" label="申请类型(CheckboxGroup)" initValue={['user', 'admin']} rules={[{ required: true }]}>
                            <FormCheckbox value="admin">admin</FormCheckbox>
                            <FormCheckbox value="user">user</FormCheckbox>
                            <FormCheckbox value="guest">guest</FormCheckbox>
                            <FormCheckbox value="root">root</FormCheckbox>
                        </FormCheckboxGroup>
                        <FormRadioGroup field="isMonopolize" label="是否独占资源(Radio)" rules={[{ type: 'boolean' }, { required: true, message: '必须选择是否独占 ' }]}>
                            <FormRadio value={1}>是</FormRadio>
                            <FormRadio value={0}>否</FormRadio>
                        </FormRadioGroup>
                    </Col>
                </Row>
                <Row>
                    <Col span={12}>
                        <FormTimePicker field="time" label="截止时刻(TimePicker)" style={{ width: '90%' }} />
                    </Col>
                    <Col span={12}>
                        <FormInputNumber field="number" label="申请数量(InputNumber)" initValue={20} style={style} />
                    </Col>
                </Row>
                <Row>
                    <Col span={12}>
                        <FormSlider field="range" label="资源使用报警阈值(%)(Slider)" initValue={10} style={{ width: '90%' }} />
                    </Col>
                    <Col span={12}>
                        <FormSwitch field="switch" label="开关(Switch)" />
                    </Col>
                </Row>
                <Row>
                    <Col span={12}>
                        <FormRating field="rating" label="满意度(Rating)" initValue={2} style={{ width: '90%' }} />
                    </Col>
                </Row>
            </Form.Section>
            <FormCheckbox value="false" field="agree" noLabel>
                我已阅读并清楚相关规定(Checkbox)
            </FormCheckbox>
            <Space>
                <Button type="primary" htmlType="submit" class="btn-margin-right">
                    提交(submit)
                </Button>
                <Button htmlType="reset">重置(reset)</Button>
            </Space>
        </Form>
    );
}

Field binding syntax

Every Field component must have a field property. This is how the form manages the state of this field. See the field syntax section below for additional details on what you can pass in for field.

The field can be a simple string, can be contained.Or[]String that supports multi-level nesting
Below is an example of the field name and their mapping path in FormState

FieldResolution
usernameformState.values.username
user[0]formState.values.user[0]
siblings.1formState.values.siblings[1]
siblings['2']formState.values.siblings[2]
parents[0].nameformState.values.parents[0].name
parents[1]['name']formState.values.parents[1].name
Code
import { Col, Form, FormInput, Row, TextArea, Toast } from '@fibrous/semi-ui-solid';

export default function FormDemo() {
    return (
        <Form onSubmit={(values) => Toast.info({ content: JSON.stringify(values) })}>
            {(form) => (
                <Row>
                    <Col span={12}>
                        <FormInput field="username" aria-label="username" placeholder="请尝试输入值" />
                        <FormInput field="user[0]" aria-label="user[0]" placeholder="请尝试输入值" />
                        <FormInput field="siblings.1" aria-label="siblings.1" placeholder="请尝试输入值" />
                        <FormInput field="siblings['2']" aria-label="siblings['2']" placeholder="请尝试输入值" />
                        <FormInput field="parents[0].name" aria-label="parents[0].name" placeholder="请尝试输入值" />
                        <FormInput field="parents[1]['name']" aria-label="parents[1]['name']" placeholder="请尝试输入值" />
                    </Col>
                    <Col span={10} offset={1} style={{ 'margin-top': '12px' }}>
                        <Form.Label text="FormState实时映射值:" />
                        <TextArea aria-label="FormState实时映射值" value={JSON.stringify(form.formState.values)} />
                    </Col>
                </Row>
            )}
        </Form>
    );
}

Form layout

  • Vertical Layout: Arrange each field vertically (By default)
    Semi Design Next recommends a vertical layout.
I have read and agree to the terms of service

Or

Code
import { Button, Form, FormCheckbox, FormInput, Toast } from '@fibrous/semi-ui-solid';

export default function FormDemo() {
    const handleSubmit = (values: Record<string, unknown>) => {
        console.log(values);
        Toast.info('表单已提交');
    };
    return (
        <Form onSubmit={(values) => handleSubmit(values)} style={{ width: '400px' }}>
            {(form) => (
                <>
                    <FormInput field="phone" label="PhoneNumber" style={{ width: '100%' }} placeholder="Enter your phone number" />
                    <FormInput field="password" label="Password" style={{ width: '100%' }} placeholder="Enter your password" />
                    <FormCheckbox field="agree" noLabel>
                        I have read and agree to the terms of service
                    </FormCheckbox>
                    <div style={{ display: 'flex', 'justify-content': 'space-between', 'align-items': 'center' }}>
                        <p>
                            <span>Or</span>
                            <Button theme="borderless" style={{ color: 'var(--semi-color-primary)', 'margin-left': '10px', cursor: 'pointer' }}>
                                Sign up
                            </Button>
                        </p>
                        <Button disabled={!form.values.agree} htmlType="submit" type="tertiary">
                            Log in
                        </Button>
                    </div>
                </>
            )}
        </Form>
    );
}
  • Horizontal Layout: Arrange each field horizontally You can use the horizontal layout by setting layout='horizontal'
Code
import { Form, FormInput } from '@fibrous/semi-ui-solid';

export default function FormDemo() {
    return (
        <Form layout="horizontal">
            <FormInput field="phone" label="PhoneNumber" placeholder="Enter your phone number" />
            <FormInput field="password" label="Password" placeholder="Enter your password" />
        </Form>
    );
}
  • Label Position, Label Align
    You can control the position of the label in the Field and the direction of text alignment by setting labelPosition, labelAlign
admin
user
guest
root
Code
import { createSignal } from 'solid-js';
import { Form, FormCheckbox, FormCheckboxGroup, FormInput, FormInputNumber, FormRadio, FormRadioGroup, FormSelect, FormSwitch, Select, type FormProps } from '@fibrous/semi-ui-solid';

const rules = [
    { required: true, message: 'required error' },
    { type: 'string' as const, message: 'type error' },
    { validator: (_rule: unknown, value: unknown) => value === 'semi', message: 'should be semi' },
];

export default function FormDemo() {
    const [labelPosition, setLabelPosition] = createSignal<FormProps['labelPosition']>('left');
    const [labelAlign, setLabelAlign] = createSignal<FormProps['labelAlign']>('left');
    const labelWidth = () => (labelPosition() === 'left' ? '180px' : 'auto');

    return (
        <>
            <div style={{ 'border-bottom': '1px solid var(--semi-color-border)', 'padding-bottom': '12px' }}>
                <Form.Label style={{ 'margin-left': '10px' }}>切换Label位置:</Form.Label>
                <Select onChange={(value) => setLabelPosition(value as FormProps['labelPosition'])} value={labelPosition()} style={{ width: '200px' }} prefix="labelPosition">
                    <Select.Option value="top">top</Select.Option>
                    <Select.Option value="left">left</Select.Option>
                </Select>
                <Form.Label style={{ 'margin-left': '10px' }}>切换Label文本对齐方向:</Form.Label>
                <Select onChange={(value) => setLabelAlign(value as FormProps['labelAlign'])} value={labelAlign()} style={{ width: '200px' }} prefix="labelAlign">
                    <Select.Option value="left">left</Select.Option>
                    <Select.Option value="right">right</Select.Option>
                </Select>
            </div>
            <Form labelPosition={labelPosition()} labelWidth={labelWidth()} labelAlign={labelAlign()} style={{ padding: '10px', width: '600px' }}>
                <FormInput field="input" label="手机号码" trigger="blur" style={{ width: '200px' }} rules={rules} />
                <FormSwitch label="是否同意" field="agree" />
                <FormInputNumber field="price" label="价格" style={{ width: '200px' }} />
                <FormSelect label="姓名" field="name" style={{ width: '200px' }}>
                    <FormSelect.Option value="mike">mike</FormSelect.Option>
                    <FormSelect.Option value="jane">jane</FormSelect.Option>
                    <FormSelect.Option value="kate">kate</FormSelect.Option>
                </FormSelect>
                <FormCheckboxGroup label="角色" field="role" direction="horizontal">
                    <FormCheckbox value="admin">admin</FormCheckbox>
                    <FormCheckbox value="user">user</FormCheckbox>
                    <FormCheckbox value="guest">guest</FormCheckbox>
                    <FormCheckbox value="root">root</FormCheckbox>
                </FormCheckboxGroup>
                <FormRadioGroup field="性别">
                    <FormRadio value="1">man</FormRadio>
                    <FormRadio value="2">woman</FormRadio>
                </FormRadioGroup>
            </Form>
        </>
    );
}
  • A more complex layout.
    You can also combine the Row and Col provided by the Grid to arrange the form structure as you want.
Code
import { Col, Form, FormDatePicker, FormInput, FormSelect, Row } from '@fibrous/semi-ui-solid';

const rules = [
    { required: true, message: 'required error' },
    { type: 'string' as const, message: 'type error' },
    { validator: (_rule: unknown, value: unknown) => value === 'semi', message: 'should be semi' },
];

export default function FormDemo() {
    return (
        <Form labelPosition="top" style={{ padding: '10px' }}>
            <Row>
                <Col span={8}>
                    <FormInput field="nickName1" label="用户名" style={{ width: '250px' }} trigger="blur" rules={rules} />
                </Col>
                <Col span={8}>
                    <FormDatePicker field="date1" label="有效日期" style={{ width: '250px' }} />
                </Col>
                <Col span={8}>
                    <FormSelect label="业务线" field="business1" style={{ width: '250px' }}>
                        <FormSelect.Option value="abc">Semi</FormSelect.Option>
                        <FormSelect.Option value="ulikeCam">轻颜相机</FormSelect.Option>
                        <FormSelect.Option value="toutiao">今日头条</FormSelect.Option>
                    </FormSelect>
                </Col>
            </Row>
            <Row>
                <Col span={6}>
                    <FormInput field="nickName2" label="用户名" style={{ width: '200px' }} trigger="blur" rules={rules} />
                </Col>
                <Col span={6}>
                    <FormDatePicker field="date2" label="有效日期" style={{ width: '200px' }} />
                </Col>
                <Col span={6}>
                    <FormSelect label="业务线" field="business2" style={{ width: '200px' }}>
                        <FormSelect.Option value="abc">Semi</FormSelect.Option>
                        <FormSelect.Option value="ulikeCam">轻颜相机</FormSelect.Option>
                        <FormSelect.Option value="toutiao">今日头条</FormSelect.Option>
                    </FormSelect>
                </Col>
                <Col span={6}>
                    <FormSelect field="role" label="角色" style={{ width: '200px' }}>
                        <FormSelect.Option value="operate">运营</FormSelect.Option>
                        <FormSelect.Option value="rd">开发</FormSelect.Option>
                        <FormSelect.Option value="pm">产品</FormSelect.Option>
                        <FormSelect.Option value="ued">设计</FormSelect.Option>
                    </FormSelect>
                </Col>
            </Row>
        </Form>
    );
}

Form grouping

Forms with many fields should group them. Use Form.Section to group Fields and pass the title through the text property (it only affects layout and does not change the data structure).

基本信息
合格标准
考试时间
分钟
到时间自动交卷
考试人员
关
Code
import { Button, Form, FormCheckbox, FormDatePicker, FormInput, FormInputNumber, FormRadio, FormRadioGroup, FormSelect, FormSwitch, Space } from '@fibrous/semi-ui-solid';

const today = new Date(2024, 4, 6, 12);

export default function FormDemo() {
    return (
        <Form style={{ width: '560px' }}>
            <Form.Section text="基本信息">
                <FormInput field="name" label="考试名称" initValue="TCS任务平台使用" style={{ width: '560px' }} />
            </Form.Section>
            <Form.Section text="合格标准">
                <div style={{ display: 'flex' }}>
                    <FormInputNumber field="pass" initValue={60} style={{ width: '80px' }} label={{ text: '及格正确率', required: true }} />
                    <FormInputNumber field="number" initValue={10} style={{ width: '80px' }} label={{ text: '合格人数', required: true }} />
                </div>
            </Form.Section>
            <Form.Section text="考试时间">
                <FormDatePicker field="date" type="dateTime" initValue={today} style={{ width: '272px' }} label={{ text: '开始时间', required: true }} />
                <div style={{ display: 'flex' }}>
                    <FormInput field="time" label="考试时长" style={{ width: '176px' }} initValue="60" addonAfter="分钟" />
                    <FormCheckbox initValue noLabel field="auto" style={{ 'padding-top': '30px', 'margin-inline-start': '12px' }}>
                        到时间自动交卷
                    </FormCheckbox>
                </div>
                <FormRadioGroup field="type" label="有效时间" direction="vertical" initValue="always">
                    <FormRadio value="always">永久有效</FormRadio>
                    <FormRadio value="user">自定义有效期</FormRadio>
                </FormRadioGroup>
                <FormRadioGroup field="answerTime" label="答案放出时间" direction="vertical" initValue="always" rules={[{ required: true }]}>
                    <FormRadio value="always">自动放出</FormRadio>
                    <FormRadio value="user">
                        <div style={{ display: 'inline-block' }}>
                            自定义放出时间
                            <FormDatePicker type="dateTimeRange" noLabel field="customTime" style={{ width: '464px', display: 'inline-block' }} />
                        </div>
                    </FormRadio>
                </FormRadioGroup>
            </Form.Section>
            <Form.Section text="考试人员">
                <div style={{ display: 'flex' }}>
                    <FormSwitch field="open" label={{ text: '对外开放', required: true }} checkedText="开" uncheckedText="关" />
                </div>
                <FormSelect field="users" label={{ text: '考生', required: true }} style={{ width: '560px' }} multiple initValue={['1', '2', '3', '4']}>
                    <FormSelect.Option value="1">曲晨一</FormSelect.Option>
                    <FormSelect.Option value="2">夏可曼</FormSelect.Option>
                    <FormSelect.Option value="3">曲晨三</FormSelect.Option>
                    <FormSelect.Option value="4">蔡妍</FormSelect.Option>
                </FormSelect>
            </Form.Section>
            <Space>
                <Button type="primary" theme="solid" style={{ width: '120px', 'margin-top': '12px', 'margin-inline-end': '4px' }}>
                    创建考试
                </Button>
                <Button style={{ 'margin-top': '12px' }}>预览</Button>
            </Space>
        </Form>
    );
}

wrapper Col / label Col

When you need to set a uniform layout for all Fields in a Form, you can set wrapperCol and labelCol on the Form to quickly generate the layout. No need to manually use Row, Col manual layout.
wrapperCol,labelColProperty Configuration Reference Col components

Code
import { Form, FormInput, FormSelect } from '@fibrous/semi-ui-solid';

export default function FormDemo() {
    return (
        <Form wrapperCol={{ span: 20 }} labelCol={{ span: 2 }} labelPosition="left" labelAlign="right">
            <FormInput field="name" style={{ width: '250px' }} label="姓名" trigger="blur" placeholder="请输入姓名" />
            <FormSelect field="role" label="角色" placeholder="请选择角色" style={{ width: '250px' }}>
                <FormSelect.Option value="operate">运营</FormSelect.Option>
                <FormSelect.Option value="rd">开发</FormSelect.Option>
                <FormSelect.Option value="pm">产品</FormSelect.Option>
                <FormSelect.Option value="ued">设计</FormSelect.Option>
            </FormSelect>
        </Form>
    );
}

Remove automatically added Label

Form will automatically insert Label for Field control. If you don't need to automatically insert the Label module, you can turn off the automatic label insertion function by setting noLabel=true in the Field (at this time, the Field still has the ability to automatically display ErrorMessage, so the DOM structure is still different from the original component)
If you want to keep the DOM structure consistent with the original component, you can use pure=true. At this time, the DOM structure will not change except that the data flow is taken over (you need to be responsible for the rendering of ErrorMessage, and it cannot be used by formProps.wrapperCol property impact)

Code
import { Form, FormInput } from '@fibrous/semi-ui-solid';

export default function FormDemo() {
    return (
        <Form onSubmit={(values) => console.log(values)} style={{ width: '400px' }}>
            <FormInput field="name" label="姓名" trigger="blur" noLabel style={{ width: '250px' }} placeholder="请输入姓名" />
            <FormInput field="purename" pure placeholder="DOM结构与普通 Input 组件完全一致" />
        </Form>
    );
}

Embedded Label

A Label can be inlined in a field control by setting labelPosition to inset. Components currently supporting this feature include Input, InputNumber, DatePicker, TimePicker, Select, TreeSelect, Cascader, TagInput, AutoComplete. With labelPosition inset, the other fields are laid out as top and warn in development mode.

A custom component wrapped with withField receives the insetLabel and insetLabelId props when labelPosition is inset: it has to render the inset label itself and write insetLabelId to the element that holds the label. A component that does not render an inset label should not be used with inset.

姓名
开始日期
Code
import { Form, FormDatePicker, FormInput, FormSelect } from '@fibrous/semi-ui-solid';

const today = new Date(2024, 4, 6, 12);

export default function FormDemo() {
    return (
        <Form labelPosition="inset" layout="horizontal">
            <FormInput field="name" label="姓名" trigger="blur" style={{ width: '250px' }} placeholder="请输入姓名" initValue="semi" />
            <FormSelect field="role" label="角色" style={{ width: '250px' }} initValue="rd">
                <FormSelect.Option value="operate">运营</FormSelect.Option>
                <FormSelect.Option value="rd">开发</FormSelect.Option>
                <FormSelect.Option value="pm">产品</FormSelect.Option>
                <FormSelect.Option value="ued">设计</FormSelect.Option>
            </FormSelect>
            <FormDatePicker field="date" label="开始日期" style={{ width: '250px' }} initValue={today} />
        </Form>
    );
}

Export Label, ErrorMessage use

When the built-in Label and ErrorMessage layout does not meet the business requirements, you need to combine the positions yourself, but you want to use the default styles of Label and ErrorMessage directly.
you can import them from the Form module, and combine Form.Label / Form.ErrorMessage by yourself.
For details of their API, refer to Label / ErrorMessage

import { Form } from '@fibrous/semi-ui-solid';
const { Label, ErrorMessage } = Form;

Use Form.Slot

When your custom component needs to maintain the same layout style as the Field component, you can place your custom component in Form.Slot
labelWidth, labelAlign, wrapperCol, labelCol set on the Form component automatically acts on Form.Slot
For the Slot property configuration, refer to Form.Slot

我是Semi Form SlotA, 我是自定义的节点
我是SlotA的ErrorMessage
我是Semi Form SlotB, 我的Label Align、Width与众不同
Code
import { Form, FormInput } from '@fibrous/semi-ui-solid';

export default function FormDemo() {
    return (
        <Form onChange={(v) => console.log(v)} onSubmit={(v) => console.log(v)} style={{ width: '600px' }} labelPosition="left" labelWidth={100}>
            <FormInput field="特效名称" style={{ width: '250px' }} />
            <Form.Slot label={{ text: 'SlotA' }} error="我是SlotA的ErrorMessage">
                <div style={{ display: 'flex', 'align-items': 'center', height: '32px', 'margin-top': '8px' }}>我是Semi Form SlotA, 我是自定义的节点</div>
            </Form.Slot>
            <Form.Slot label={{ text: 'SlotB', width: 160, align: 'right' }}>
                <div style={{ display: 'flex', 'align-items': 'center', height: '100%' }}>我是Semi Form SlotB, 我的Label Align、Width与众不同</div>
            </Form.Slot>
        </Form>
    );
}

Use helpText、extraText set prompt information

You can place custom prompt information (a string or JSX) through helpText, and display it in the same block as the verification information (error). When both have values, the verification information will be displayed first.
Additional prompt information can be placed through extraText. When the error message and prompt text need to appear at the same time, this property can be used. It is always displayed and located after helpText/error
When validateStatus is passed in, the UI style corresponding to the value of validateStatus will be displayed first. If not passed in, the internal verification status of the field shall prevail.

Code
import { createSignal } from 'solid-js';
import { Form, FormInput, type CommonFieldProps, type FormElement, type InputValidateStatus as ValidateStatus } from '@fibrous/semi-ui-solid';

export default function FormDemo() {
    const [weak, setWeak] = createSignal(false);
    const [validateStatus, setValidateStatus] = createSignal<ValidateStatus>('default');
    let form: FormElement | undefined;

    const validator: CommonFieldProps['validator'] = (val) => {
        if (!val) {
            setValidateStatus('error');
            return <span>密码不能为空</span>;
        } else if (val.length <= 3) {
            setValidateStatus('warning');
            setWeak(true); // 展示 helpText
            return ''; // 校验通过
        }
        setWeak(false);
        setValidateStatus('success');
        return '';
    };

    const random = () => {
        const pw = (Math.random() * 100000).toString().slice(0, 5);
        form?.formApi.setValue('Password', pw);
        form?.formApi.setError('Password', '');
        setWeak(false);
        setValidateStatus('success');
    };

    return (
        <Form showValidateIcon ref={(node) => (form = node)} onSubmit={() => console.log('submit success')} onSubmitFail={(errors) => console.log(errors)}>
            <FormInput
                validator={validator}
                field="Password"
                validateStatus={validateStatus()}
                helpText={weak() ? <span style={{ color: 'var(--semi-color-warning)' }}>密码强度:弱</span> : ''}
                extraText={
                    <button
                        type="button"
                        style={{
                            padding: 0,
                            border: 'none',
                            background: 'none',
                            font: 'inherit',
                            color: 'var(--semi-color-link)',
                            'font-size': '14px',
                            'user-select': 'none',
                            cursor: 'pointer',
                        }}
                        onClick={random}
                    >
                        没有想到合适的密码?点击随机生成一个
                    </button>
                }
            />
        </Form>
    );
}

By configuring extraTextPosition, you can control the display position of extraText. Optional values bottom, middle
For example, when you want to display the extraText prompt information between the Label and Field component.
This attribute can be configured uniformly on the Form or individually on each Field. When passing in at the same time, the configuration of the Field shall prevail.

未勾选时,默认为红点提醒,消息默认进入收件人消息列表。对于重要通知,可同时勾选相应的通知方式。
飞书通知
邮件通知
顶部横幅通知
对于对话框通知,可指定该消息必须在指定时长后才可置为已读。
Code
import { Form, FormCheckboxGroup, FormInputNumber } from '@fibrous/semi-ui-solid';

const options = [
    { label: '飞书通知', value: 'lark' },
    { label: '邮件通知', value: 'email' },
    { label: '顶部横幅通知', value: 'notification' },
];

const notifyText = '未勾选时,默认为红点提醒,消息默认进入收件人消息列表。对于重要通知,可同时勾选相应的通知方式。';
const forceText = '对于对话框通知,可指定该消息必须在指定时长后才可置为已读。';

export default function FormDemo() {
    return (
        <Form extraTextPosition="middle">
            <FormCheckboxGroup direction="horizontal" field="notify" label="通知方式" extraText={notifyText} options={options} />
            <FormInputNumber field="force" label="强制读取(可选)" placeholder="秒" extraText={forceText} extraTextPosition="bottom" />
        </Form>
    );
}

Using Input Group

When you need to combine some fields to use, you can use Form.InputGroup to wrap them. The fields inside no longer render their own Label and ErrorMessage, and their errors are shown together below the group.
But usually, in Form.InputGroup you only need a Label belonging to the entire Group. You can set the label property in the Form.InputGroup to insert a Label belonging to the Group
label configurable properties, see Label

Code
import { Button, Form, FormInput, FormSelect } from '@fibrous/semi-ui-solid';

export default function FormDemo() {
    return (
        <Form onSubmit={(values) => console.log(values)} labelPosition="top" style={{ width: '400px' }}>
            <Form.InputGroup label={{ text: <span>手机号码</span>, required: true }} labelPosition="top">
                <FormSelect style={{ width: '150px' }} field="phonePrefix" initValue="+86" rules={[{ required: true }]} showClear>
                    <FormSelect.Option value="+1">美国+1</FormSelect.Option>
                    <FormSelect.Option value="+852">香港+852</FormSelect.Option>
                    <FormSelect.Option value="+86">中国+86</FormSelect.Option>
                    <FormSelect.Option value="+81">日本+81</FormSelect.Option>
                </FormSelect>
                <FormInput initValue="18912345678" style={{ width: '250px' }} field="phoneNumber" rules={[{ required: true }]} showClear />
            </Form.InputGroup>
            <FormInput field="姓名" trigger="blur" initValue="Semi" />
            <Button htmlType="submit">提交</Button>
        </Form>
    );
}

Form in the Modal pop-up layer

You can place the Form in Modal and load it as a popup.
When submitting, use formApi.validate() to centrally verify the Field

Code
import { createSignal } from 'solid-js';
import { Button, Col, Form, FormInput, FormSelect, Modal, Row, type FormApi } from '@fibrous/semi-ui-solid';

const message = '该项为必填项';

export default function FormDemo() {
    const [visible, setVisible] = createSignal(false);
    let formApi: FormApi | undefined;

    const handleOk = () => {
        formApi
            ?.validate()
            .then((values) => {
                console.log(values);
            })
            .catch((errors) => {
                console.log(errors);
            });
    };

    return (
        <>
            <Button onClick={() => setVisible(true)}>打开弹窗</Button>
            <Modal title="新建" visible={visible()} onOk={handleOk} style={{ width: '600px' }} onCancel={() => setVisible(false)}>
                <Form getFormApi={(api) => (formApi = api)}>
                    <Row>
                        <Col span={5}>
                            <FormSelect field="region" label="国家/地区" placeholder="请选择" style={{ width: '100%' }} rules={[{ required: true, message }]}>
                                <FormSelect.Option value="China">中国</FormSelect.Option>
                                <FormSelect.Option value="US">美国</FormSelect.Option>
                                <FormSelect.Option value="Europe">欧洲</FormSelect.Option>
                                <FormSelect.Option value="Japan">日本</FormSelect.Option>
                            </FormSelect>
                        </Col>
                        <Col span={15} offset={2}>
                            <FormInput field="owner" label="业务执行人" trigger="blur" rules={[{ required: true, message }]} />
                        </Col>
                    </Row>
                    <Row>
                        <Col span={5}>
                            <FormSelect field="area" label="投放区域" placeholder="请选择" style={{ width: '100%' }} rules={[{ required: true, message }]}>
                                <FormSelect.Option value="China">中国</FormSelect.Option>
                                <FormSelect.Option value="US">美国</FormSelect.Option>
                                <FormSelect.Option value="Europe">欧洲</FormSelect.Option>
                                <FormSelect.Option value="Japan">日本</FormSelect.Option>
                            </FormSelect>
                        </Col>
                        <Col span={15} offset={2}>
                            <FormInput field="department" label="业务执行部门" trigger="blur" rules={[{ required: true, message }]} />
                        </Col>
                    </Row>
                </Form>
            </Modal>
        </>
    );
}

Configure initial values and verification rules

  • You can configure check rules for each Field through rules
    The verification library inside the Form is based on async-validator, and more configuration rules can be found in its official documentation
  • You can uniformly set the initial value for the entire form through the initValues of form, or you can set the initial value through initValue in each field (the latter has a higher priority)
  • You can configure different verification trigger timings for each Field through trigger, and the default is change (that is, the verification is performed automatically when the value changes). Also supports change, blur, mount, custom or a combination of the above. It also supports unified configuration through FormProps. If both are configured, FieldProps shall prevail
  • You can use the stopValidateWithError switch to decide whether to continue to trigger the validation of subsequent rules when the first rule that fails the validation is encountered. Unified configuration through FormProps is also supported. If both are configured, FieldProps shall prevail
Code
import { Button, Form, FormInput } from '@fibrous/semi-ui-solid';

const initValues = {
    name: 'semi',
    shortcut: 'se',
};

const style = { width: '100%' };

const rules = [
    { required: true, message: 'required error' },
    { type: 'string' as const, message: 'type error' },
    { validator: (_rule: unknown, value: unknown) => value === 'semi', message: 'should be semi' },
    {
        validator: (_rule: unknown, value: unknown) => Boolean(typeof value === 'string' && value.startsWith('se')),
        message: 'should startsWith se',
    },
];

export default function FormDemo() {
    return (
        <Form initValues={initValues}>
            <FormInput field="name" style={style} trigger="blur" rules={rules} />
            <FormInput field="shortcut" style={style} stopValidateWithError rules={rules} />
            <Button htmlType="submit">提交</Button>
        </Form>
    );
}

Custom Validate (Form Level)

You can set a custom validation function for the Form as a whole with validator. It will be called on submit or when calling formApi.validate().

Synchronous Validate

When validate success, you should return an empty string.
When validate fails, you should return the error message (Object, key is fieldName, value is the corresponding error message)

Code
import { Button, Form, FormInput } from '@fibrous/semi-ui-solid';

interface FormValues {
    name?: string;
    sex?: string;
}

const syncValidate = (values: FormValues) => {
    const errors: Record<string, unknown> = {};
    if (values.name !== 'mike') {
        errors.name = 'you must name mike';
    }
    if (values.sex !== 'female') {
        errors.sex = 'must be woman';
    }
    errors.familyName = [{ before: 'before error balabala ', after: 'after error balabala' }, 'familyName[1] error balabala'];
    return errors;
};

export default function FormDemo() {
    return (
        <Form validator={syncValidate} layout="horizontal">
            <FormInput field="name" trigger="blur" />
            <FormInput field="familyName[0].before" trigger="blur" />
            <FormInput field="familyName[0].after" trigger="blur" />
            <FormInput field="familyName[1]" trigger="blur" />
            <div style={{ display: 'flex', 'align-items': 'flex-end' }}>
                <Button type="primary" htmlType="submit" class="btn-margin-right">
                    Submit
                </Button>
                <Button htmlType="reset">reset</Button>
            </div>
        </Form>
    );
}

Asynchronous Validate

For asynchronous validation, you should return a promise. In promise.then() you need to return the corresponding error message.

Code
import { Button, Form, FormInput } from '@fibrous/semi-ui-solid';

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

interface FormValues {
    name?: string;
    sex?: string;
}

const asyncValidate = (values: FormValues) =>
    sleep(2000).then(() => {
        const errors: FormValues = {};
        if (values.name !== 'mike') {
            errors.name = 'you must name mike';
        }
        if (values.sex !== 'female') {
            errors.sex = 'sex not valid';
        }
        return errors;
    });

export default function FormDemo() {
    return (
        <Form validator={asyncValidate} layout="horizontal">
            <FormInput field="name" trigger="blur" />
            <FormInput field="familyName[0].before" trigger="blur" />
            <FormInput field="familyName[1]" trigger="blur" />
            <FormInput field="sex" trigger="blur" />
            <div style={{ display: 'flex', 'align-items': 'flex-end' }}>
                <Button type="primary" htmlType="submit" class="btn-margin-right">
                    Submit
                </Button>
                <Button htmlType="reset">reset</Button>
            </div>
        </Form>
    );
}

Custom Validate (Field Level)

You can specify a custom validation function for a single Field with validator. Supports synchronous and asynchronous validation (by returning promises)

Code
import { Button, Form, FormInput } from '@fibrous/semi-ui-solid';

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

const validateName = (val?: string) => {
    if (!val) {
        return "【sync】can't be empty";
    } else if (val.length <= 5) {
        return '【sync】must more than 5';
    }
    return '';
};

const asyncValidate = (val?: string) =>
    sleep(2000).then(() => {
        if (!val) {
            return "【async】can't be empty";
        } else if (val.length <= 5) {
            return '【async】must more than 5';
        } else {
            return '';
        }
    });

export default function FormDemo() {
    return (
        <Form>
            <FormInput field="name" label="【name】asyncValidate after 2s" validator={asyncValidate} trigger="blur" />
            <FormInput field="familyName" label="【familyName】syncValidate" validator={validateName} trigger="blur" />
            <Button htmlType="reset">reset</Button>
        </Form>
    );
}

Manually Trigger specified validation

When you want to manually trigger the validation of some specific Field, you can do it through formApi.validate.
When no parameters are passed in, all Fields are checked by default. When parameters are passed in, the parameters specified shall prevail

Silent Validation

When you need to get the validation result without triggering UI updates (no error messages shown, no touched state set), you can use formApi.validate({ silent: true }). This is useful in scenarios where you want to decide whether to make a backend request based on the validation result.

Code
import { Button, Form, FormInput, Toast, type FormApi } from '@fibrous/semi-ui-solid';

export default function FormDemo() {
    let formApi: FormApi | undefined;

    const handleSilentValidate = () => {
        formApi
            ?.validate({ silent: true })
            .then((values) => {
                Toast.success('表单校验通过,准备发起请求');
                console.log('发起后端请求:', values);
            })
            .catch((errors) => {
                Toast.error('表单校验未通过,但不显示错误提示');
                console.log('校验错误:', errors);
            });
    };

    const handleNormalValidate = () => {
        formApi
            ?.validate()
            .then(() => {
                Toast.success('表单校验通过');
            })
            .catch(() => {
                Toast.error('表单校验未通过,显示错误提示');
            });
    };

    return (
        <Form getFormApi={(api) => (formApi = api)} layout="horizontal">
            <FormInput
                field="username"
                label="用户名"
                rules={[
                    { required: true, message: '用户名不能为空' },
                    { min: 3, message: '用户名至少 3 个字符' },
                ]}
            />
            <FormInput
                field="email"
                label="邮箱"
                rules={[
                    { required: true, message: '邮箱不能为空' },
                    { type: 'email', message: '邮箱格式不正确' },
                ]}
            />
            <div style={{ display: 'flex', gap: '12px', 'margin-top': '12px' }}>
                <Button onClick={handleSilentValidate} type="primary">
                    静默校验(不显示错误)
                </Button>
                <Button onClick={handleNormalValidate}>普通校验(显示错误)</Button>
            </div>
        </Form>
    );
}
a
b
c
d
b.name
a
b
c
d
b.name
Code
import { Button, Form, FormCheckboxGroup, FormInput, Space, Toast, type FormApi } from '@fibrous/semi-ui-solid';

const allFields = ['a', 'b', 'c', 'd', 'b.name'];
const options = allFields.map((item) => ({ label: item, value: item }));

const validate = (val?: string) => {
    if (!val) {
        return "can't be empty";
    } else if (val.length <= 5) {
        return <span>我是传入的节点</span>;
    }
    return;
};

export default function FormDemo() {
    let formApi: FormApi | undefined;

    const validatePartial = (type?: 'all') => {
        const scope = type === 'all' ? allFields : (formApi?.getValue('validateScope') ?? []);
        formApi
            ?.validate(scope)
            .then((values) => {
                console.log(values);
                Toast.success('pass');
            })
            .catch((error) => {
                Toast.error('error');
                console.log(error);
            });
    };

    const resetPartial = () => {
        formApi?.reset(formApi.getValue('resetScope'));
    };

    return (
        <Form getFormApi={(api) => (formApi = api)} autoScrollToError layout="horizontal">
            {(form) => (
                <>
                    <div>
                        <FormInput field="a[1]" validator={validate} trigger="blur" />
                        <FormInput field="a[0]" validator={validate} trigger="blur" />
                        <FormInput field="b.name[0]" validator={validate} trigger="blur" />
                        <FormInput field="b.name[1]" validator={validate} trigger="blur" />
                        <FormInput field="b.type" validator={validate} trigger="blur" />
                        <FormInput field="c" validator={validate} trigger="blur" />
                        <FormInput field="d" validator={validate} trigger="blur" />
                    </div>
                    <div>
                        <FormCheckboxGroup options={options} field="validateScope" label="当前希望校验的Field" initValue={['a', 'b']} direction="horizontal" />
                        <FormCheckboxGroup options={options} field="resetScope" label="当前需要Reset的Field" direction="horizontal" />
                        <Space>
                            <Button htmlType="reset">reset</Button>
                            <Button onClick={() => validatePartial('all')}>all validate</Button>
                            <Button onClick={() => validatePartial()}>partial validate {JSON.stringify(form.values.validateScope)}</Button>
                            <Button onClick={resetPartial}>partial reset</Button>
                        </Space>
                    </div>
                </>
            )}
        </Form>
    );
}

Linkage Fields

You can achieve the linkage between Fields by listening to the onChange of Field and then using formApi (for example saved through getFormApi) to make modifications.

Note will change after Sex select
Code
import { Button, Form, FormInput, FormSelect, Row, type FormApi } from '@fibrous/semi-ui-solid';

export default function FormDemo() {
    let formApi: FormApi | undefined;

    const handleSelectChange = (value: unknown) => {
        const text = value === 'male' ? 'Hi male' : 'Hi female!';
        formApi?.setValue('Note', text);
    };

    return (
        <Form getFormApi={(api) => (formApi = api)} onValueChange={(values) => console.log(values)} style={{ width: '250px' }}>
            <span>Note will change after Sex select</span>
            <FormInput field="Note" style={{ width: '250px' }} />
            <FormSelect field="Sex" onChange={handleSelectChange} style={{ width: '250px' }}>
                <FormSelect.Option value="female">female</FormSelect.Option>
                <FormSelect.Option value="male">male</FormSelect.Option>
            </FormSelect>
            <Row>
                <Button type="primary" htmlType="submit" class="btn-margin-right">
                    Submit
                </Button>
                <Button htmlType="reset">reset</Button>
            </Row>
        </Form>
    );
}

Dynamic form

Dynamically add and delete fields

Code
import { Show } from 'solid-js';
import { Button, Form, FormInput, FormRadio, FormRadioGroup } from '@fibrous/semi-ui-solid';

export default function FormDemo() {
    return (
        <Form style={{ width: '450px' }}>
            {(form) => (
                <>
                    <FormInput field="name" label="用户名称:" />
                    <FormRadioGroup field="isAnchor" label="是否已注册主播">
                        <FormRadio value="yes">yes</FormRadio>
                        <FormRadio value="no">no</FormRadio>
                    </FormRadioGroup>
                    <Show when={form.formState.values.isAnchor === 'yes'}>
                        <FormInput field="liveRoom" label="直播间名称" />
                    </Show>
                    <Button htmlType="submit">提交</Button>
                </>
            )}
        </Form>
    );
}

Keep empty values (allowEmpty)

By default a field whose value becomes empty is removed from values. Set allowEmpty on a Field to keep its key with an undefined value, or on Form to apply it to every field. Clear both selects below and compare the keys of values.

["keep","drop"]
Code
import { Form, FormSelect } from '@fibrous/semi-ui-solid';

const initValues = { keep: 'admin', drop: 'admin' };

const roleOptions = [
    { label: '管理员', value: 'admin' },
    { label: '访客', value: 'guest' },
];

export default function FormDemo() {
    return (
        <Form initValues={initValues}>
            {(form) => (
                <>
                    <FormSelect field="keep" label="设置了 allowEmpty" allowEmpty showClear optionList={roleOptions} style={{ width: '176px' }} />
                    <FormSelect field="drop" label="未设置" showClear optionList={roleOptions} style={{ width: '176px' }} />
                    <code>{JSON.stringify(Object.keys(form.values))}</code>
                </>
            )}
        </Form>
    );
}

Keep field state on unmount (keepState)

By default, when a Field component is unmounted, its value, error, and touched state are all reset. If you want to preserve these states after the field is unmounted (for example, in conditional rendering scenarios), you can use the keepState property.

显示条件字段
Code
import { Show, createSignal } from 'solid-js';
import { Button, Form, FormInput, FormSwitch, Switch } from '@fibrous/semi-ui-solid';

export default function FormDemo() {
    const [show, setShow] = createSignal(true);

    return (
        <Form style={{ width: '450px' }}>
            <FormSwitch field="alwaysShow" label="始终显示的字段" />
            <Switch aria-labelledby="form-keep-state-toggle" checked={show()} onChange={(checked) => setShow(checked)} style={{ 'margin-bottom': '12px' }} />
            <span id="form-keep-state-toggle" style={{ 'margin-left': '8px', color: 'var(--semi-color-text-2)' }}>
                显示条件字段
            </span>
            <Show when={show()}>
                <FormInput field="conditionalField" label="条件字段(keepState)" keepState />
                <FormInput field="noKeepState" label="条件字段(无 keepState)" />
            </Show>
            <Button htmlType="submit">提交</Button>
        </Form>
    );
}

In the example above:

  • The field with keepState will retain its previously entered value, validation state, etc. after being hidden and then shown again
  • The field without keepState will have its state reset after being hidden and then shown again

ArrayField Usage

For array items that are dynamically added or deleted, we provide the ArrayField component to simplify the operation of adding and removing rows. The children of ArrayField is a function that is called once, with { arrayFields, add, addWithInitValue }: add and addWithInitValue add a blank row or a row with an initial value, and the remove of each item in arrayFields deletes that row.

Render the rows with <For each={props.arrayFields}>. A row object keeps its identity while the row exists, and its field follows the rows added or removed before it.

For the detailed API of ArrayField, please refer to ArrayField below

Note: The initValue type of ArrayField must be an array

Code
import { For } from 'solid-js';
import { IconMinusCircle, IconPlusCircle } from '@fibrous/semi-icons-solid';
import { ArrayField, Button, Form, FormInput, FormSelect, TextArea, useFormState } from '@fibrous/semi-ui-solid';

const data = [
    { name: 'Semi D2C', role: 'Engineer' },
    { name: 'Semi C2D', role: 'Designer' },
];

const roleOptions = [
    { label: 'Engineer', value: 'Engineer' },
    { label: 'Designer', value: 'Designer' },
];

function ComponentUsingFormState() {
    const formState = useFormState();
    return <TextArea aria-label="Form state" style={{ 'margin-top': '10px' }} value={JSON.stringify(formState())} />;
}

export default function FormDemo() {
    return (
        <Form style={{ width: '800px' }} labelPosition="left" labelWidth="100px" allowEmpty>
            <ArrayField field="rules" initValue={data}>
                {(props) => (
                    <>
                        <Button onClick={props.add} icon={<IconPlusCircle />} theme="light">
                            Add new line
                        </Button>
                        <Button icon={<IconPlusCircle />} onClick={() => props.addWithInitValue({ name: 'Semi DSM', role: 'Designer' })} style={{ 'margin-left': '8px' }}>
                            Add new line with init value
                        </Button>
                        <For each={props.arrayFields}>
                            {(row) => (
                                <div style={{ width: '1000px', display: 'flex' }}>
                                    <FormInput field={`${row.field}[name]`} label={`${row.field}.name`} style={{ width: '200px', 'margin-right': '16px' }} />
                                    <FormSelect field={`${row.field}[role]`} label={`${row.field}.role`} style={{ width: '120px' }} optionList={roleOptions} />
                                    <Button type="danger" theme="borderless" aria-label="Delete" icon={<IconMinusCircle />} onClick={row.remove} style={{ margin: '12px' }} />
                                </div>
                            )}
                        </For>
                    </>
                )}
            </ArrayField>
            <ComponentUsingFormState />
        </Form>
    );
}

Nesting ArrayField

ArrayField supports multi-level nesting. The following is an example of two-level nesting.

当邮件到达,满足以下条件时:
当邮件到达,满足以下条件时:
Code
import { For } from 'solid-js';
import { IconMinusCircle, IconPlusCircle } from '@fibrous/semi-icons-solid';
import { ArrayField, Button, Card, Form, FormInput, FormSelect, Typography } from '@fibrous/semi-ui-solid';

const selectOption = [
    { label: '发件人地址', value: 'address' },
    { label: '邮件主题', value: 'title' },
    { label: '发送时间', value: 'sendTime' },
    { label: '接收时间', value: 'receiveTime' },
    { label: '正文', value: 'main' },
    { label: '附件名称', value: 'attachmentName' },
];

const typeOption = [
    { label: '包含', value: 'include' },
    { label: '不包含', value: 'exclude' },
];

const initValue = {
    group: [
        {
            name: '收信规则1',
            rules: [
                { ruleType: 'address', type: 'include', text: 'bytedance.com' },
                { ruleType: 'title', type: 'exclude', text: '更新日志' },
            ],
        },
        {
            name: '收信规则2',
            rules: [{ ruleType: 'sendTime', type: 'include', text: '2019' }],
        },
    ],
};

const rowStyle = {
    'margin-top': '12px',
    'margin-left': '12px',
};

function NestedField(props: { field: string }) {
    return (
        <ArrayField field={`${props.field}.rules`}>
            {(rules) => (
                <For each={rules.arrayFields}>
                    {(row, i) => (
                        <div style={{ display: 'flex' }}>
                            <FormSelect field={`${row.field}[ruleType]`} label={`${row.field}.ruleType`} noLabel optionList={selectOption} style={{ width: '120px', 'margin-right': '12px' }} />
                            <FormSelect field={`${row.field}[type]`} label={`${row.field}.type`} noLabel style={{ width: '100px', 'margin-right': '12px' }} optionList={typeOption} />
                            <FormInput field={`${row.field}[text]`} label={`${row.field}.text`} aria-label="条件内容" noLabel style={{ width: '200px' }} />
                            <Button type="danger" theme="borderless" style={rowStyle} aria-label="删除条件" icon={<IconMinusCircle />} onClick={row.remove} />
                            <Button
                                aria-label="新增条件"
                                icon={<IconPlusCircle />}
                                style={rowStyle}
                                disabled={i() !== rules.arrayFields.length - 1}
                                onClick={() =>
                                    rules.addWithInitValue({
                                        ruleType: `条件${rules.arrayFields.length + 1}`,
                                        type: 'include',
                                    })
                                }
                            />
                        </div>
                    )}
                </For>
            )}
        </ArrayField>
    );
}

export default function FormDemo() {
    return (
        <Form onValueChange={(values) => console.log(values)} initValues={initValue} labelPosition="left" style={{ 'text-align': 'left' }} allowEmpty>
            <ArrayField field="group">
                {(group) => (
                    <>
                        <Button
                            icon={<IconPlusCircle />}
                            theme="solid"
                            onClick={() =>
                                group.addWithInitValue({
                                    name: '新规则名称',
                                    rules: [
                                        { ruleType: 'main', type: 'include', text: '' },
                                        { ruleType: 'attachmentName', type: 'include', text: '' },
                                    ],
                                })
                            }
                        >
                            新增收信规则
                        </Button>
                        <For each={group.arrayFields}>
                            {(row) => (
                                <div style={{ width: '1000px', display: 'flex', 'flex-wrap': 'wrap' }}>
                                    <FormInput field={`${row.field}[name]`} labelPosition="top" label="规则名称" style={{ width: '600px' }} />
                                    <Button type="danger" style={{ margin: '36px 0 0 12px' }} aria-label="删除规则" icon={<IconMinusCircle />} onClick={row.remove} />
                                    <Typography.Text strong style={{ 'flex-basis': '100%' }}>
                                        当邮件到达,满足以下条件时:
                                    </Typography.Text>
                                    <Card shadows="hover" style={{ width: '620px', margin: '12px 0 0 24px' }}>
                                        <NestedField field={row.field} />
                                    </Card>
                                </div>
                            )}
                        </For>
                    </>
                )}
            </ArrayField>
        </Form>
    );
}

Add or delete form items dynamically - by use formApi

If you don't use ArrayField, you can use the provided formApi to manually add or delete formState.

Code
import { Index, Show } from 'solid-js';
import { Button, Form, FormInput, FormSelect, TextArea, type FormApi } from '@fibrous/semi-ui-solid';

interface Effect {
    name: string;
    type: string;
    key: number;
}

interface FormValues {
    effects: Effect[];
}

const initValues: FormValues = {
    effects: [
        { name: '脸部贴纸', type: '2D', key: 1 },
        { name: '背景贴纸', type: '3D', key: 2 },
    ],
};

export default function FormDemo() {
    let formApi: FormApi<FormValues> | undefined;
    let nextKey = 3;

    const add = () => {
        const effects = formApi?.getValue('effects') ?? [];
        formApi?.setValue('effects', [...effects, { name: '', type: '', key: nextKey++ }]);
    };

    const remove = (key: number) => {
        const effects = (formApi?.getValue('effects') ?? []).filter((effect: Effect) => key !== effect.key);
        formApi?.setValue('effects', effects.length ? effects : undefined);
    };

    return (
        <Form<FormValues> getFormApi={(api) => (formApi = api)} initValues={initValues} style={{ width: '500px' }} labelPosition="left" labelWidth="180px">
            {(form) => (
                <>
                    <Button onClick={add}>添加</Button>
                    {/* fields are bound by position, so rows are tracked by index, not by object identity */}
                    <Show when={form.values.effects}>
                        <Index each={form.values.effects}>
                            {(effect, i) => (
                                <div style={{ width: '1000px', display: 'flex' }}>
                                    <FormInput field={`effects[${i}].name`} aria-label={`特效 ${i + 1} 名称`} style={{ width: '200px', 'margin-right': '12px' }} />
                                    <FormSelect field={`effects[${i}].type`} style={{ width: '90px' }}>
                                        <FormSelect.Option value="2D">2D</FormSelect.Option>
                                        <FormSelect.Option value="3D">3D</FormSelect.Option>
                                    </FormSelect>
                                    <Button type="danger" onClick={() => remove(effect().key)} style={{ margin: '12px' }}>
                                        删除
                                    </Button>
                                </div>
                            )}
                        </Index>
                    </Show>
                    <TextArea aria-label="表单值" style={{ 'margin-top': '10px' }} value={JSON.stringify(form.formState.values)} />
                </>
            )}
        </Form>
    );
}

Use of Hook

We provide four hooks so that you can easily access Form internal state and call Form and Field related api in a component placed inside the Form structure without passing through props. They depend on the context provided by Form; outside a Form, useFormApi returns an empty object and the accessor of useFormState gives an empty object

import { useFormApi, useFormState, useFieldApi, useFieldState } from '@fibrous/semi-ui-solid';

useFormApi

useFormApi allows you to directly access the formApi of the parent Form component within a component inside the Form

Code
import { Button, Form, FormInput, useFormApi } from '@fibrous/semi-ui-solid';

function ComponentUsingFormApi() {
    const formApi = useFormApi();
    const change = () => {
        formApi.setValue('name', Math.random());
    };
    return <Button onClick={change}>ChangeName By【formApi】</Button>;
}

export default function FormDemo() {
    return (
        <Form>
            <FormInput field="name" initValue="mike" />
            <ComponentUsingFormApi />
        </Form>
    );
}

useFormState

useFormState allows you to directly access the form State of the parent Form component within a component inside the Form. It returns an accessor (Accessor<FormState>), read through formState(), which follows the form when read in JSX

FormState read by 【useFormState】:
{"values":{},"errors":{},"touched":{}}
Code
import { Form, FormInput, useFormState } from '@fibrous/semi-ui-solid';

function ComponentUsingFormState() {
    const formState = useFormState();
    return (
        <pre>
            <code>{JSON.stringify(formState())}</code>
        </pre>
    );
}

export default function FormDemo() {
    return (
        <Form>
            <FormInput field="name" initValue="mike" />
            <h5>FormState read by 【useFormState】:</h5>
            <ComponentUsingFormState />
        </Form>
    );
}

useFieldApi

useFieldApi allows you to call the api of the specified Field directly within a component inside the Form. The parameter can be a field name or an accessor that returns one, which follows the field name when it changes

Code
import { Button, Form, FormInput, useFieldApi } from '@fibrous/semi-ui-solid';

function ComponentUsingFieldApi() {
    const nameFieldApi = useFieldApi('name');
    const change = () => {
        nameFieldApi.setValue(Math.random());
    };
    return <Button onClick={change}>Click Me!!! changeNameBy【fieldApi】</Button>;
}

export default function FormDemo() {
    return (
        <Form>
            <FormInput field="name" initValue="mike" />
            <ComponentUsingFieldApi />
        </Form>
    );
}

useFieldState

useFieldState allows you to directly access the State of the specified Field within a component inside the Form. The parameter can be a field name or an accessor that returns one, and it returns an accessor: fieldState() gives { value, error, touched }

【name】FieldState read by 【useFieldState】:{}
【country】FieldState read by 【useFieldState】:{}
Code
import { Form, FormInput, useFieldState } from '@fibrous/semi-ui-solid';

function ComponentUsingFieldState(props: { field: string }) {
    const fieldState = useFieldState(() => props.field);
    return (
        <div>
            <span>【{props.field}】FieldState read by 【useFieldState】:</span>
            <code>{JSON.stringify(fieldState())}</code>
        </div>
    );
}

export default function FormDemo() {
    return (
        <Form layout="horizontal">
            <div style={{ width: '400px' }}>
                <FormInput field="name" initValue="mike" />
                <FormInput field="country" initValue="china" />
            </div>
            <div style={{ width: '500px', 'margin-top': '30px' }}>
                <ComponentUsingFieldState field="name" />
                <ComponentUsingFieldState field="country" />
            </div>
        </Form>
    );
}

Access formApi and formState through the render function

Solid has no withFormApi or withFormState. The render function of Form (and the children function and component) already provides formApi and formState; use useFormApi and useFormState above inside a child component

Access formApi

Code
import { Button, Form, FormInput } from '@fibrous/semi-ui-solid';

export default function FormDemo() {
    return (
        <Form>
            {(form) => (
                <>
                    <FormInput field="name" initValue="semi" />
                    <FormInput field="familyName" initValue="design" />
                    <Button htmlType="submit" style={{ 'margin-right': '4px' }}>
                        submit
                    </Button>
                    <Button onClick={() => form.formApi.setValue('name', Math.random())}>Click Me!!! ChangeName By【formApi】</Button>
                </>
            )}
        </Form>
    );
}

Access formState

{"values":{},"errors":{},"touched":{}}
Code
import { Form, FormInput } from '@fibrous/semi-ui-solid';

export default function FormDemo() {
    return (
        <Form>
            {(form) => (
                <>
                    <FormInput field="name" initValue="semi" />
                    <FormInput field="familyName" initValue="design" />
                    <code>{JSON.stringify(form.formState)}</code>
                </>
            )}
        </Form>
    );
}

Take over custom components

Via withField, you can extend other custom components into Field. Form will taking over its behavior.

With Field did the following things.

  • Take over the value of the component (or other properties specified by valueKey), the onChange callback (or other callbacks specified by onKeyChangeFnName)
  • Insert Field's Form.Label above the field
  • Insert Field's Form.ErrorMessage under the field
  • Insert Field's extraText under the field

With Field Options specific configuration can be consulted withFieldOption

Your custom controlled component needs to do the following:

  • Read the value through props.value (or the property specified by valueKey) and update your component UI rendering results. Do not destructure props, or the component stops following the value
  • When the value changes, call props.onChange (or the callback specified by onKeyChangeFnName) with the latest value as the argument
withField(YourComponent, withFieldOption);

When wrapping a native input, wrap it in a small component first as the demo does, so that props injected by the Form such as validateStatus do not land on the DOM. The native onChange of Solid fires on blur; to keep the value in sync while typing, set onKeyChangeFnName to 'onInput' together with valuePath: 'target.value'.

The props type of the returned component is inferred from the props of YourComponent: the component's own props plus Field Props, without value, defaultValue, checked and defaultChecked (the Form owns the value).

{"values":{},"errors":{},"touched":{}}
Code
import { type ComponentProps, splitProps } from 'solid-js';
import { Form, useFormState, withField } from '@fibrous/semi-ui-solid';

// validateStatus stays off the DOM; a native input fires change on blur, so the field listens to input instead
function HtmlInput(props: ComponentProps<'input'> & { validateStatus?: string }) {
    const [, rest] = splitProps(props, ['validateStatus', 'value']);
    return <input {...rest} value={props.value ?? ''} />;
}

const CustomInput = withField(HtmlInput, {
    valueKey: 'value',
    onKeyChangeFnName: 'onInput',
    valuePath: 'target.value',
});

function ComponentUsingFormState() {
    const formState = useFormState();
    return (
        <pre>
            <code>{JSON.stringify(formState())}</code>
        </pre>
    );
}

export default function FormDemo() {
    return (
        <Form>
            <CustomInput field="name" />
            <ComponentUsingFormState />
        </Form>
    );
}
名称
{"values":{},"errors":{},"touched":{}}
Code
import { Form, Input, Select, useFormState, withField } from '@fibrous/semi-ui-solid';

interface BaseInfo {
    name?: string;
    role?: string;
}

interface MyComponentProps {
    id?: string;
    value?: BaseInfo;
    onChange?: (value: BaseInfo) => void;
    'aria-labelledby'?: string;
    'aria-required'?: boolean;
}

const roles = [
    { value: 'rd', label: '开发' },
    { value: 'UED', label: '设计师' },
];

// id and aria-labelledby go on the fieldset (named by the field label); aria-required goes to each control
function MyComponent(props: MyComponentProps) {
    const handleChange = (patch: BaseInfo) => props.onChange?.({ ...props.value, ...patch });
    return (
        <fieldset class="customField" id={props.id} aria-labelledby={props['aria-labelledby']} style={{ border: '0', margin: '0', padding: '0' }}>
            <Input aria-label="名称" aria-required={props['aria-required']} prefix="名称" value={props.value?.name} onChange={(name) => handleChange({ name })} style={{ width: '180px', 'margin-right': '12px' }} />
            <Select aria-label="角色" aria-required={props['aria-required']} prefix="角色" value={props.value?.role} onChange={(role) => handleChange({ role: role as string | undefined })} style={{ width: '200px' }} optionList={roles} />
        </fieldset>
    );
}

const CustomField = withField(MyComponent, { valueKey: 'value', onKeyChangeFnName: 'onChange' });

function ComponentUsingFormState() {
    const formState = useFormState();
    return (
        <pre>
            <code>{JSON.stringify(formState())}</code>
        </pre>
    );
}

export default function FormDemo() {
    return (
        <Form>
            <CustomField field="baseInfo" label={{ text: '基本信息', required: true }} />
            <ComponentUsingFormState />
        </Form>
    );
}

API reference

Form

import { Form } from '@fibrous/semi-ui-solid';

Props

PropertyDescriptionTypeDefault
allowEmptyWhether a field whose value becomes empty keeps its key in values. Setting it to true on either the Form or the field takes effect.booleanfalse
autoScrollToErrorWhether to scroll to the first invalid field when submit or formApi.validate fails. An object is passed to scroll-into-view-if-needed as its options.boolean | ScrollOptionsfalse
childrenThe content of the form. A function is called once, like render, with { formState, values, formApi }; read them in the returned JSX to follow the form.TypeJSX.Element | ((props: FormRenderProps<Values>) => JSX.Element)-
componentA component that declares the fields, rendered with formState, values and formApi as its props. Do not use it together with render or children.Type(props: FormRenderProps<Values>) => JSX.Element-
disabledThe disabled state applied to every field. A field's own disabled takes precedence.boolean-
extraTextPositionPosition of the extra text of every field: middle puts it between the label and the control, bottom after the control. The same property on a field takes precedence.'middle' | 'bottom'-
formThe formApi returned by Form.useForm(), used to control the form from outside.TypeFormApi<Values> & FormApiProxyInternals<Values>-
getFormApiCalled once the Form has mounted, with the formApi.Type(formApi: FormApi<Values>) => void-
idThe id of the form element, also written to x-form-id. Generated when omitted.string-
initValuesInitial values of the form, copied once when the Form is created.Values-
labelAlignText alignment of the label of every field. The same property on a field takes precedence.'left' | 'right'-
labelColGrid layout of the label of every field, with the properties of Col such as span and offset. Set it together with wrapperCol.ColProps-
labelPositionLabel position of every field. inset is supported by some fields only; the others are laid out as top. The same property on a field takes precedence.'top' | 'left' | 'inset'"top"
labelWidthLabel width of every field. A number is in px.number | string-
layoutDirection in which the fields are arranged: vertical or horizontal.'horizontal' | 'vertical'"vertical"
onChangeCalled when the form state changes: a field mounts, unmounts, changes its value, blurs, or changes its validation state or error. Receives formState.Type(formState: FormState<Values>) => void-
onErrorChangeCalled when validation state changes, with all errors and the errors that changed. Batch operations such as validate, submit and reset call it once; silent validation does not.Type(errors: AllErrors<Values>, changedError?: Partial<Record<FieldPath<Values>, FieldError>>) => void-
onResetCalled when a reset button is clicked or formApi.reset is called.Type() => void-
onSubmitCalled when a submit button is clicked or formApi.submitForm is called and validation passes, with values and the submit event.Type(values: Values, e?: SubmitEvent) => void-
onSubmitFailCalled when a submit button is clicked or formApi.submitForm is called and validation fails, with errors, values and the submit event.Type(errors: FormValidateResult<Values>, values: Partial<Values>, e?: SubmitEvent) => void-
onValueChangeCalled when a field value changes, with all values and the values that changed.Type(values: Values, changedValue: Partial<Values>) => void-
refReceives the form element, which carries the formApi.Type(element: FormElement<Values>) => void-
renderA function that declares the fields. It is called once, with { formState, values, formApi }. Do not use it together with component or children.Type(props: FormRenderProps<Values>) => JSX.Element-
showValidateIconWhether the validation message is preceded by an icon of its status.booleantrue
stopPropagationWhether to stop the submit and reset events from bubbling, so that a nested Form does not trigger the events of the outer one.{ submit?: boolean; reset?: boolean; }-
stopValidateWithErrorWhether to skip the remaining rules after the first rule fails. The same property on a field takes precedence.boolean-
triggerWhen every field validates: change, blur, mount, custom, or an array of them. The same property on a field takes precedence.FieldValidateTriggerType-
validatorForm-level validation, called on submit and formApi.validate and allowed to return a Promise. When set, the validator and rules of the fields no longer apply. An empty string or object means valid; on failure return an object keyed by field name.Type(values: Values) => FormValidateResult<Values> | Promise<FormValidateResult<Values>>-
wrapperColGrid layout of the control of every field, with the properties of Col such as span and offset. Set it together with labelCol.ColProps-

class, style, ref and native attributes and events (such as aria-* and onKeyDown) land on the form element. When labelCol and wrapperCol are set, the form is wrapped in a Row, and the other attributes still land on the form. The form element has novalidate by default, so only Semi validates; pass novalidate={false} to restore native validation.

The form element received by ref carries the formApi (type FormElement).

FormState

FormState stores all the state values within the Form, including the values of each field, error information, touched status

NameInstructionsInitial valueExample
valuesValue Collection of the form{}{fieldA: 'str', fieldB: true}
errorsForm error information collection, you can decide whether to allow users to submit by judging whether there is error information{}{fieldA: 'length not valid'}
touchedThe collection of fields the user has clicked on{}{fieldA: true}

How to access the form state

  • By calling formApi.getFormState()
  • Via the child render function, formState will injected as a parameter
  • Via the render props, formState will injected as a parameter
  • Via useFormState in a component inside the Form
  • Via the formState created by Form.useForm(), read as an accessor outside the Form

FormApi

We provide FormApi. You have easy access to FormApi both inside and outside the Form, which allows you to use getter and setter to get and manipulate the values of FormState.
The table below describes the features available in the formApi.

FunctionDescriptionexample
getFormPropsGet Form Component PropsformApi.getFormProps(propNames?: string[])
getFormStateGet FormStateformApi.getFormState()
submitFormManually submit form operationformApi.submitForm()
resetReset the form manuallyformApi.reset(fields?: Array <string>)
validateManually trigger validation of the entire form. the verification of the entire Field will be triggered by default when no parameters are passed , if you want to trigger the verification of some fields, pass in the target field array

After the Form level validator is configured, the Field level validator will not be triggered again when submit or formApi.validate()

Silent validation: Pass { silent: true } to get validation results without triggering UI updates (no error messages shown, no touched state set). You can also use { fields: ['fieldA'], silent: true } to perform silent validation on specific fields.
formApi.validate()
.then(values => {})
.catch(errors => {})
OR formApi.validate(['fieldA','fieldB'])
OR formApi.validate({ silent: true })
OR formApi.validate({ fields: ['fieldA'], silent: true })
setValuesSet the values of the entire form. The isOverride in the second parameter is false by default.
When isOverride is false: Iterate through all registered fields in the Form, and update the values from newValues to formState.values. If a registered field is not included in newValues, that field will be set to undefined.
When isOverride is true: Directly replace formState.values with newValues, including extra keys in newValues that don't have corresponding fields in the form.

Recommended usage: If you only need to update some fields, it's recommended to use formApi.setValue(field, value) for individual updates, or get current values first then merge: formApi.setValues({ ...formApi.getValues(), name: newValue })
formApi.setValues(newValues: object, {isOverride: boolean})
getValuesGet the values of all FieldformApi.getValues()
setValueprovides direct modification of formState.values method.
The difference from setValues is that it only modifies a single field.
formApi.setValue(field: string, newFieldValue: any)
getValueGet the value of all / single FieldformApi.getValue()
formApi.getValue(field: string)
setTouchedModify formState.touchedformApi.setTouched(field: string, isTouched: boolean)
getTouchedGet the touched state of the FieldformApi.getTouched(field: string)
setErrorModify the error information of a fieldformApi.setError(field: string, fieldErrorMessage: string)
getErrorGet Error Status of FieldformApi.getError(field: string)
getFieldExistGet whether the field exists in the FormformApi.getFieldExist(field: string)
scrollToFieldScroll to the specified field, the second input parameter will be passed to scroll-into-view-if-neededformApi.scrollToField(field: string, scrollOpts: ScrollIntoViewOptions)
scrollToErrorScroll to the field with validation error. You can pass a specified field or index. If you pass index, scroll to the index-th error DOM. If you do not pass any parameters, scroll to the first validation error position in the DOM tree.formApi.scrollToError(ScrollToErrorOptions{field?: string; index?: number; scrollOpts?: ScrollIntoViewOptions })

How to access formApi

  • Use Form.useForm() to create formApi outside Form, then pass it via the form property to the Form component. This allows you to get formApi before Form renders, suitable for scenarios where you need to control the form from outside the component.
  • After the Form component mounts, it calls the getFormApi callback passed in props. You can save a reference to formApi in the callback function for subsequent calls (example code below) In addition, we provide other ways to get formApi, and you can choose different ways of calling
  • Use the ref callback to get the form element, you can access its formApi
  • Via the child render function, formApi will injected as a parameter
  • Via the render props, formApi will injected as a parameter
  • Via useFormApi for children component of Form

Using Form.useForm()

Form.useForm() (also available as the useForm import) is used to create a formApi outside the Form component, suitable for scenarios where you need to control the form before it renders. It returns an array [formApi, formState, formValues]: formState and formValues are accessors that follow the form once bound through the form property of Form, read through formState() and formValues().

Usage example:

表单值:{}
touched 状态:{}
Code
import { Button, Form, FormInput } from '@fibrous/semi-ui-solid';

export default function FormDemo() {
    const [formApi, formState, formValues] = Form.useForm();

    const handleClick = () => {
        formApi.setValue('username', 'semi');
        console.log('当前表单值:', formValues());
    };

    return (
        <>
            <Button onClick={handleClick}>外部设置值</Button>
            <Button onClick={() => formApi.reset()}>重置表单</Button>

            <Form form={formApi}>
                <FormInput field="username" label="用户名" />
                <FormInput field="email" label="邮箱" />
            </Form>

            <div style={{ 'margin-top': '16px' }}>
                <div>表单值:{JSON.stringify(formValues())}</div>
                <div>touched 状态:{JSON.stringify(formState().touched)}</div>
            </div>
        </>
    );
}
import { Button, Form, FormInput } from '@fibrous/semi-ui-solid';

function FormApiDemo() {
    let formApiA;
    let formB;

    const changeValues = () => {
        // use formApi to update formA. After getting the formApi object, you can use it to make any changes you want to the form
        formApiA?.setValues({ a: 1 });
        // use formApi to update formB
        formB?.formApi.setValues({ b: 2 });
    };

    return (
        <>
            {/* save the formApi from the getFormApi callback */}
            <Form getFormApi={(formApi) => (formApiA = formApi)}>
                <FormInput field="a" />
            </Form>
            {/* read the formApi from the form element received by ref */}
            <Form ref={(node) => (formB = node)}>
                <FormInput field="b" />
            </Form>
            <Button onClick={changeValues}>Change</Button>
        </>
    );
}

Field Props

A Field is a component made by withField; the table below lists its own properties.

PropertiesDescriptionTypeDefault
convertAfter the field value changes, before it is stored in formState and shown, update the value of the field(fieldValue) => any
fieldThe mapping path of the field's value in formState.values. Form will use this value to distinguish the internal form control.
Required!!! (except a FormCheckbox or FormRadio inside its group)
string
labelThe label text for this field. When not passed, it defaults to the same name as field. An object is passed to Form.Label as its properties and can set text, extra, required, optional, align, width and disabled, see Label. text and extra can be JSXLabelProps | JSX.Element
labelPositionLabel position of this field. When passed on both Form and Field, the Field props prevail'top' | 'left' | 'inset'
labelAlignText-align of the label text of this field. When passed on both Form and Field, the Field props prevail'left' | 'right'
labelWidthThe width of the label text of this field, a number is in px. When passed on both Form and Field, the Field props prevailstring | number
labelColGrid layout of the label of this field, with Col component. It overrides the same property of Form. When it is set together with wrapperCol while the Form does not set both, the Field wraps itself in a RowColProps
wrapperColGrid layout of the control of this field, with Col component. It overrides the same property of Form. Used the same way as labelColColProps
noLabelWhen you don't need to add label automatically, you can set this value to trueboolean
noErrorMessageWhen you don't need to add the ErrorMessage module automatically, you can set this value to true. Note that helpText is not shown eitherboolean
nameField name. When passed in, the corresponding className will be automatically added to the field wrapper div, such as: money => '.semi-form-field-money'. It is also passed to the underlying component, for example to configure the name attribute of an inputstring
idThe id of the control, generated when omitted. The for of the label and the ids of the label, helpText, extraText and errormessage are derived from itstring
fieldClassNameThe className of the entire fieldWrapper is the same as the name parameter, except that the prefix is not automatically appendedstring
fieldStyleThe inline style of the entire fieldWrapperJSX.CSSProperties | string
initValueThe initial value of the field (consumed only once when Field mounted, subsequent updates are invalid), it has higher priority than the values in Form's initValuesany (type depends on current component)
validatorThe custom validation function for this form control. Supports synchronous and asynchronous validation (by returning a promise). An empty string or undefined means valid; any other result (a string, JSX or an array) is the error. When validator is set, rules will not take effect(fieldValue, values) => FieldValidateResult | Promise<FieldValidateResult>
rulesvalidation rules, validation library based on async-validatorRuleItem[]
validateStatusThe validation result status of this form control, which only affects the style, optional: success / error / warning / default. When omitted, the Field's own validation status is usedstring
triggerThe timing of triggering the verification, optional: blur / change / custom / mount, or an array of them
1. When set to custom, only formApi will trigger the verification
2.mount (triggered once when mounting)
FieldValidateTriggerType'change'
onChangeCallback when the value changes. The parameters are those of the callback of the wrapped component, followed by the latest form values latestValues; a FormCheckbox or FormRadio without field is a plain control and has no latestValues (see the onChange of each component)(...args, latestValues) => void
onBlurCallback when the field loses focus (see the onBlur of each component)(...args) => void
transformtransform field values before validation. The transformed value is only used for validation and does not affect formState(fieldValue) => any
allowEmptyWhether to keep the key of this field in values (as undefined) when its value is empty. Setting it on either the Field or the Form takes effectbooleanfalse
allowEmptyStringWhether to allow values to be empty strings.
When the value is '' by default, the key corresponding to this field will be removed from values.
If you want to keep the key, you need to set allowEmptyString to true
booleanfalse
emptyValueThe value that counts as empty. When the value changes to it, the key of this field is removed from values (kept as undefined when allowEmpty is true)unknown''
keepStateWhether to retain the field state (value, error, touched) after the field is unmounted. When true, the field's value, validation message, and interaction state are preserved after unmounting, and will be automatically restored upon remountingbooleanfalse
stopValidateWithErrorWhen it is true, the rules check is used. After encountering the first rule that fails the check, it will no longer trigger the check of subsequent rulesbooleanfalse
helpTextCustom prompt information, which is displayed in the same block as the verification information. When both have values, the verification information is displayed firstJSX.Element
extraTextAdditional prompt information, you can use this when both error information and prompt copy are required, after helpText/errorMessageJSX.Element
pureWhether to only take over the data stream, when true, it will not automatically insert modules such as ErrorMessage, Label, extraText, etc. The style and DOM structure are consistent with the original componentsbooleanfalse
extraTextPositioncontrols the display position of extraText. Middle (the vertical direction is displayed in the order of Label, extraText, and Field), bottom (the vertical direction is displayed in the order of Label, Field, and extraText); when passed on both Form and Field, the Field props prevail'middle' | 'bottom''bottom'
...otherOther configurable properties of the component, passed in together with the above properties, such as size and placeholder of Input. The Field passes them, together with class, style, ref and aria-*, to the wrapped component itself, not to the fieldWrapper

disabled takes the value of the Form and a disabled written on the Field wins.

Field Api

We also provide fieldApi, most of which is similar to formApi, with the difference that fieldApi limits the scope of modification, and it can only modify the bound field. Get it through useFieldApi

FunctionInstructionsexample
setValueModify the value of the current FieldfieldApi.setValue(newValue: any)
getValueGets the value of the current FieldfieldApi.getValue()
setTouchedModify the touched state of the current FieldfieldApi.setTouched(true)
getTouchedGet the touched state of the current FieldfieldApi.getTouched()
setErrorModify the error information of the current FieldfieldApi.setError(newErrorMessage: string)
getErrorGets field's error statusfieldApi.getError()

ArrayField

For dynamically added and deleted array form items, we provide the ArrayField scope to simplify adding and removing rows

import { ArrayField } from '@fibrous/semi-ui-solid';

Props

PropertyDescriptionTypeDefault
childrenRequired. A function that renders the rows. It is called once, with { arrayFields, add, addWithInitValue }; read arrayFields in the returned JSX to follow the rows.Type(props: ArrayFieldChildrenProps) => JSX.Element-
fieldRequired. Path of the array in formState.values. For rows with fields a[0].name and a[1].name pass a.string-
initValueInitial value of the array, which must be an array. It takes precedence over the initValues of the Form.any[]-

ArrayField has no DOM of its own, so undeclared attributes are dropped. The argument of the children function has this type:

interface ArrayFieldChildrenProps {
    readonly arrayFields: ArrayFieldRow[]; // The current array form, which can be used to render each row
    add: (index?: number | MouseEvent) => void; // Add a blank line; a number inserts it at that position, an event is ignored so it can be used directly as onClick
    addWithInitValue: (lineObject: Record<string, any> | string, index?: number) => void; // Add a new row with an initial value, index is the insert position
}

interface ArrayFieldRow {
    key: string; // A key used to identify the current row
    readonly field: string; // This row fieldPath, which is equivalent to the field of ArrayField + [index], and follows the rows added or removed before it
    remove: () => void; // Remove operation function of this line, when called, this line will be deleted directly
}

Form.Section

import { Form } from '@fibrous/semi-ui-solid';
const { Section } = Form;

Props

PropertyDescriptionTypeDefault
textThe title of the section. No title is rendered when it has no content.JSX.Element-

class, style, ref and native attributes land on the section element.

Form.Label

By default, Label is self-inserted into each Field by Form.
If you need to self-insert Label elsewhere, we have provided the Label component for you.

import { Form } from '@fibrous/semi-ui-solid';
const { Label } = Form;

Props

PropertyDescriptionTypeDefault
alignText alignment of the label: left or right.string-
disabledWhether the label looks disabled.boolean-
extraContent after the label text.JSX.Element-
nameThe id of the labeled control, written to the for attribute. for is used when it is not set.string-
optionalWhether to append the optional text of the locale. When true, the * of required is hidden.boolean-
requiredWhether to display the required * symbol.boolean-
textText of the label. children is used when it is not set.JSX.Element-
widthWidth of the label. A number is in px.number | string-

class, style, ref and native attributes land on the label element.

Form.InputGroup

import { Form } from '@fibrous/semi-ui-solid';
const { InputGroup } = Form;

Props

PropertyDescriptionTypeDefault
disabledThe disabled state applied to the fields in the group. Falls back to the Form's disabled when not set.boolean-
extraTextExtra text of the group, positioned by extraTextPosition.JSX.Element-
extraTextPositionPosition of the extra text: middle puts it between the label and the group, bottom after the group. Defaults to bottom.'bottom' | 'middle'-
labelLabel of the whole group: an object is the label configuration, whose id becomes the id of the label, and any other content is the label text.LabelProps | JSX.Element-
labelPositionLabel position. Defaults to the Form's, and can be top or left.'left' | 'top'-
onBlurCalled as focus leaves any control in the group, also for a move to another control in it.Type(e: FocusEvent) => void-
onFocusCalled as any control in the group takes focus, also for a move from another control in it.Type(e: FocusEvent) => void-
sizeSize of every control in the group: small, default or large.InputSize-

class, style and ref land on the role="group" element of the inner InputGroup, and the other native attributes (such as aria-*) are passed to every field in the group. aria-labelledby and aria-describedby are merged with the ids generated by the group, the caller's first. The outer element has role="group" when a label is set, and has none without a label. Form.InputGroup works inside a Form only; outside one it renders nothing and logs a warning.

When extraTextPosition is middle and labelPosition is left. Since the content of extraText has a variable height, the Label will no longer ensure that it can be aligned with the first line of text in the Field / InputGroup.

Form.Slot

import { Form } from '@fibrous/semi-ui-solid';
const { Slot } = Form;

Props

PropertyDescriptionTypeDefault
errorThe error, rendered after the content: an object is the props of ErrorMessage and any other content is the error. Nothing shows when omitted.ErrorMessageProps | JSX.Element-
labelThe text of the label, or a label configuration such as text, extra, align, width, required and optional.LabelProps | JSX.Element-
labelPositionLabel position. Defaults to the Form's, and can be top or left.'top' | 'left'-
noLabelWhether to render no label. When the Form sets both labelCol and wrapperCol, the label column is still kept.boolean-

class, style, ref and native attributes land on the root element. The root element has role="group" when a label is set or aria-label or aria-labelledby is passed, and a role passed by the caller wins. The label width and alignment come from labelWidth and labelAlign of the Form, and width and align in the label object win.

Form.ErrorMessage

import { Form } from '@fibrous/semi-ui-solid';
const { ErrorMessage } = Form;
  • When the error is a string or JSX, render directly; when it is true, only the error container is rendered, without text; when it is false, nothing is rendered
  • When the error is an array, the errors in the array are aggregated and joined with commas

Props

PropertyDescriptionTypeDefault
errorThe error. A string or JSX is shown as is and an array is joined. true shows the error container without text; false and empty values render nothing.FieldError-
errorMessageIdThe id of the error text element, referenced by aria-errormessage.string-
helpTextThe help text. It shares the block with the error, and the error is shown when both are set.JSX.Element-
helpTextIdThe id of the help text element, referenced by aria-describedby.string-
isInInputGroupWhether it is inside an InputGroup. When it and showValidateIcon are true, the error icon shows whatever validateStatus is.boolean-
showValidateIconWhether to show the icon of validateStatus.boolean-
validateStatusValidation status of the message: default, error, warning or success.string-

class, style, ref and native attributes land on the root element.

withFieldOption

keyDescriptionDefault
valueKeyThe property of the component that represents the value, such as checked of Switch and value of Input'value'
onKeyChangeFnNameThe name of the callback property the component calls when its value changes, generally onChange; use onInput for a native input that should sync while typing'onChange'
valuePathThe path of the value in the first argument of the callback, such as target.value of RadioGroup and of the native input; if the first argument is the value itself, as in Switch, there is no need to take the value down, the item does not need to be set''
shouldInjectWhen false, a component without field is rendered as it is and not taken over by the Form, such as a FormCheckbox or FormRadio inside its group; when true and there is no field, a warning is logged in development modetrue

Accessibility

ARIA

  • aria-labelledby、for
    • Field component will automatically add label DOM. The id of the control is props.id, generated when omitted; the for attribute of label is the same as this id; the id attribute of label is ${control id}-label;
    • When the props.labelPosition of the Form or Field is set to inset, there is no label tag at this time, but a div tag. The div tag corresponding to insetLabel will be automatically appended with id, the value is the same as the id of the above label, corresponding to the aria-labelledby of the Field component. A field that does not support the inset label is laid out as top, and its aria-labelledby points to the label actually rendered
    • The Field component will be automatically appended with aria-labelledby, the value is the same as the id of the above label; the aria-labelledby passed by the caller comes first and the two are merged instead of overwritten
  • aria-required
    • When the Field is configured with required fields (that is, props.rules contains require: true or props.label is configured with required: true without optional: true), the Field component will be automatically appended with aria-required = true (except CheckboxGroup, Slider, Upload and a single Radio); an aria-required passed on the Field takes precedence
  • aria-invalid 、aria-errormessage
    • When the Field check fails, or validateStatus is error, the Field component will be automatically added with the aria-invalid = true attribute.
    • When the Field check fails, the Field component will be automatically appended with the aria-errormessage attribute, the value of which is the id of the DOM element corresponding to the errorMessage (format like: ${control id}-errormessage); for CheckboxGroup it is set on every checkbox in the group.
  • aria-describedby
    • When the Field is configured with helpText or extraText, the Field component will be automatically added with the aria-describedby attribute, whose value is the id of the DOM element corresponding to helpText and extraText (format like: ${control id}-helpText , ${control id}-extraText); the aria-describedby passed by the caller comes first and the two are merged instead of overwritten

Content Guidelines

  • Form title
    • The title of the form needs to follow the writing specification of the title
  • Form label
    • The label is a short description of the input box. The label is not a help text, so it should not be a description of the input
    • Labels must:
      • Place it above or below the input box
      • Short (1-3 words)
      • Use case conventions for statements (first letter uppercase, others lowercase)
  • Help text
    • Help text use statement writing conventions, capitalized
  • Form button

Design Tokens

These are the component's internal Sass variables and cannot be overridden. To customize styles, override the --semi-* CSS variables (see the Design Token page) or write unlayered CSS rules.
Sass variableValueUsage
$spacing-form_field_horizontal-paddingRight$spacing-base水平布局表单项右侧内边距
$spacing-form_field_group_horizontal-paddingRight$spacing-base水平布局表单组标题右侧内边距
$spacing-form_field_vertical-paddingTop$spacing-base-tight表单项顶部内边距(垂直布局)
$spacing-form_field_vertical-paddingBottom$spacing-base-tight表单项底部内边距(垂直布局)
$spacing-form_field_group_vertical-paddingTop$spacing-base-tight垂直布局表单组顶部内边距
$spacing-form_field_group_vertical-paddingBottom$spacing-base-tight垂直布局表单组底部内边距
$spacing-form_label-paddingRight$spacing-base表单项标签右侧边距(水平布局)
$spacing-form_label-paddingTop($height-control-default - 20px) * 0.5表单项标签顶部内边距(水平布局)
$spacing-form_label-marginBottom$spacing-extra-tight表单项标签底部外边距
$spacing-form_label-marginTop0px表单项标签顶部外边距
$spacing-form_label_extra-marginLeft$spacing-extra-tight表单项标签额外信息左侧边距
$spacing-form_label_required-marginLeft$spacing-extra-tight表单项标签必填标志左侧边距
$spacing-form_label_posLeft-marginRight0表单项左侧标签右侧外边距
$spacing-form_label_posLeft-marginBottom0表单项左侧标签底部外边距
$spacing-form_label_posTop-paddingTop$spacing-extra-tight表单项顶部标签顶部边距
$spacing-form_label_posTop-paddingBottom$spacing-extra-tight表单项顶部标签底部边距
$spacing-form_extra_posMid-marginTop$spacing-extra-tight表单项额外提示信息顶部外边距 - 额外信息处于中间时
$spacing-form_extra_posMid-marginBottom$spacing-extra-tight表单项额外提示信息底部外边距 - 额外信息处于中间时
$spacing-form_extra_posBottom-marginTop$spacing-extra-tight表单项额外提示信息顶部外边距 - 额外信息处于底部时
$spacing-form_switch_rating_marginY($height-control-default - 24px) * 0.5Switch / Rating 表单项顶部内边距(水平布局)
$color-form_requiredMark_disabled-text-defaultvar(--semi-color-danger)禁用表单项必填标记颜色
$color-form_label_disabled-text-defaultvar(--semi-color-disabled-text)禁用表单项标签文字颜色
$font-form_label-fontWeight$font-weight-bold表单项标签字重
$color-form_label-text-defaultvar(--semi-color-text-0)表单项标签文字颜色
$color-form_label_optional-text-defaultvar(--semi-color-tertiary)表单项标签可选标记颜色
$color-form_label_extra-text-defaultvar(--semi-color-tertiary)表单项标签图标颜色
$color-form_requiredMark-text-defaultvar(--semi-color-danger)必填标记颜色
$font-form_requiredMark-fontWeight$font-weight-bold表单必填标识字重
$color-form_message_error-text-defaultvar(--semi-color-danger)错误提示颜色
$color-form_alertIcon-icon-defaultvar(--semi-color-warning)警告图标颜色
$spacing-form_statusIcon-marginRight$spacing-extra-tight表单校验状态图标右侧外边距
$spacing-form_message-marginTop$spacing-extra-tight表单错误信息、辅助文字顶部外边距
$color-form_section-text-defaultvar(--semi-color-text-0)表单分组标题文字颜色
$color-form_section-border-defaultvar(--semi-color-border)表单分组标题底部描边颜色
$width-form_section-border$border-thickness-control表单分组标题底部描边宽度
$spacing-form_section-marginTop$spacing-super-loose - $spacing-base-tight表单分组顶部内边距
$spacing-form_section_text-paddingBottom$spacing-tight表单分组标题底部内边距
$spacing-form_section_text-marginBottom$spacing-extra-tight表单分组标题底部外边距
$spacing-form_section_text-paddingTop0px表单分组标题顶部内边距
$spacing-form_section_text-marginTop0px表单分组标题顶部外边距

FAQ

  • Why did I declare the form, modify the value, and the data is not automatically mapped to formState.values?
    Check that the field has been passed correctly, and the field attribute on the Field component is a must-fill property !

  • Why doesn't the passed defaultValue or defaultChecked take effect?
    Refer to the beginning of the document Field. The Field component unifies the default value. You should pass the default value using initValue or initValues

  • Why did the component not change and the value not take effect after initValue and initValues were updated asynchronously?
    initValue, initValues are only consumed once when Field and Form mount, and subsequent asynchronous updates will not take effect.
    If your initial value needs to be taken remotely, you can update it using formApi.setValue / setValues after you get the value
    Or send a new key directly to Form or Field to force it to remount.

  • Why can't getValues get a certain field?

    If the field has no initial value, getValues cannot get this item. You can set initValues/initValue or set the allowEmpty attribute to the form.

  • Why does hitting enter on the input box trigger the form's submit?

    This is standard HTML behavior. We do not plan to intervene and we will remain the same as the HTML. If there is really only one input element in the form, and you don't want to trigger the submit callback when you press Enter, it is recommended to use preventDefault for the enter of the keydown event of input to prevent the default behavior.

    Click #767 for background and content.

  • The form will automatically save the historical input items, what should I do if I don't want this function?
    Before v2.3, Form did not configure for, name, id and other attributes for input controls strictly according to the A11y accessibility standard, so this function was not available in previous versions. After v2.3, we implemented it strictly according to the W3C standard. If you don't want the browser to automatically save history input items, you can also turn it off by setting autoComplete=off at the Form level or Field level