React Suite组件表单验证
React Suite 是一个前端库,包含了在企业应用中使用的各种React组件。本文讨论了React Suite的表单验证如何帮助开发人员添加表单验证。表单验证涉及在表单中输入的数据有错误时向用户提供提示信息。表单验证有助于确保输入的表单数据是合乎逻辑并按照规定顺序提交的。
在rsuite中,我们可以使用以下方法来验证表单数据:
- 使用rsuite的Schema
- 使用schema-typed库的SchemaModel
在rsuite中的默认验证: 在提交事件被触发后(即用户点击提交按钮),表单会自动触发数据验证。这涉及将输入的表单数据作为props传递给一个函数,该函数会在提交事件被触发后检查TextField中的数据。
Schema模型: 使用Schema Model创建数据模型的语法
import { Schema } from "rsuite"
const model = Schema.Model({
// Here we declare the following properties
name: Schema.Types.StringType()
.isRequired('This field is required.'),
email: Schema.Types.StringType()
.isEmail('Please enter a valid email address.')
});
在上面的模式图中,我们声明了一个包含模式的模型:姓名和电子邮件。
字段级验证规则: 字段级验证涉及为每个字段或字段数组提供单独的值验证函数。
在rsuite中添加字段级验证的规则如下:
- 使用
<Form.control>
来添加字段级验证。 - 使用 rule 属性。
- 规则名称应该使用Schema.Types.StringType()在规则后定义为变量。
异步检查: 异步检查涉及在数据输入表单时验证数据。需要对数据执行异步验证的条件包括验证用户名是否重复或电子邮件是否已存在。这有助于用户快速识别输入的数据是否唯一。
自定义Form.Control: Form.Control组件用于数据管理和与Form组件相关的数据。
- 用于在Form中绑定数据字段,将name属性传递给Schema.Model对象的键。
- 默认为Input组件,可以通过accepter组件进行设置。
第三方库: 当我们想要自定义表单组件并使其适合表单需求时,可以使用第三方库。
自定义触发验证: 在某些情况下,不需要实时验证表单数据。可以自定义控件的验证方式并配置checkTrigger参数。
checkTrigger的默认选项是’change’,它在数据发生变化时触发验证。还包括:
- ‘blur’: 在组件失去焦点时触发验证
- ‘none’: 在调用表单的check方法时有效
动态表单验证: 这有助于动态更改验证规则。这在表单接受2个输入字段:开始日期和结束日期时可以更好地理解。因此,开始日期不应大于结束日期。为了避免在组件文件中进行编码,可以使用动态表单验证。
使用的Props和方法:
- Form props
- Schema API
创建React应用程序并安装rsuite模块:
步骤1: 使用以下命令创建React App
npx create-react-app foldername
这可能需要几秒钟时间,接下来,
步骤2:使用终端导航到文件夹
cd foldername
步骤3: 创建ReactJS应用后,使用以下命令安装所需模块
npm install rsuite
项目结构应如下所示:
示例1: 在这个示例中,我们将说明默认的检查,打开src文件夹中的App.js文件,并写入以下代码。
import { Form, Button, ButtonToolbar, Schema, Panel } from 'rsuite';
const { StringType } = Schema.Types;
const model = Schema.Model({
name: StringType().isRequired('This field is required.'),
email: StringType()
// Checks for email format on default trigger
.isEmail('Please enter a valid email address.')
.isRequired('This field is required.')
});
function TextField(props) {
const { name, label, accepter, ...rest } = props;
return (
<Form.Group controlId={`${name}-3`}>
<Form.ControlLabel>{label} </Form.ControlLabel>
<Form.Control name={name} accepter={accepter} {...rest} />
</Form.Group>
);
}
function App() {
return (
<Form model={model}>
<TextField name="name" label="Username" />
<TextField name="email" label="Email" />
<ButtonToolbar>
<Button appearance="primary" type="submit">
Submit
</Button>
</ButtonToolbar>
</Form>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
要运行该应用程序,请在终端中输入以下命令。
npm start
输出:
示例2: 在这个示例中,我们将使用异步检查。
打开src文件夹中的App.js文件,并写入以下代码:
import React from 'react';
import 'rsuite/dist/rsuite.min.css'
import { Form, Button, ButtonToolbar,
Schema, FlexboxGrid } from 'rsuite';
const { StringType } = Schema.Types;
function asyncCheckUsername(name) {
return new Promise(resolve => {
setTimeout(() => {
// Add the condition for asynchronous check
if (name === 'rsuite')
// rsuite will be the already registered name
{
resolve(false);
}
else {
resolve(true);
}
}, 500);
})
}
const model = Schema.Model({
name: StringType().addRule((value) => {
// Check the entered name
return asyncCheckUsername(value);
}, 'Username already exists')
.isRequired('This field is required')
})
export default function App() {
const formRef = React.useRef()
const handleSubmit = () => {
// When handling form submission
formRef.current.checkAsync().then(result => {
console.log(result);
})
}
return (
<FlexboxGrid.Item colspan={12}>
<FlexboxGrid.Item colspan={12}>
<Form
model={model}
>
<Form.Group controlId="name-2">
<Form.ControlLabel>
Type a Username
</Form.ControlLabel>
<Form.Control checkAsync name="name"
placeholder="Try to enter rsuite" />
</Form.Group>
<ButtonToolbar>
<Button appearance="primary"
onClick={handleSubmit}>
Submit
</Button>
</ButtonToolbar>
</Form>
</FlexboxGrid.Item>
</FlexboxGrid.Item>
)
}
输出:
示例3: 打开src文件夹中的App.js文件,并写入以下代码,
import React from 'react'
import { Form, Schema } from 'rsuite'
import 'rsuite/dist/rsuite.min.css'
const { StringType } = Schema.Types
const model = Schema.Model({
password: StringType()
.isRequired('This field is required'),
verifyPassword: StringType()
.addRule((value, data) => {
if (value !== data.password) {
return false
}
return true
},
'Passwords do not match')
.isRequired('This field is required')
});
// Pass information for the form label and control
// within the form group at once
const TextField = React.forwardRef((props, ref) => {
const { name, label, accepter, ...rest } = props;
return (
<Form.Group controlId={`${name}-4`} ref={ref}>
<Form.ControlLabel>{label} </Form.ControlLabel>
<Form.Control name={name} accepter={accepter} {...rest} />
</Form.Group>
);
});
export default function App() {
const formRef = React.useRef()
const [formValue, setFormValue] = React.useState({
password: '',
verifyPassword: ''
})
return (
<div style={{ margin: 30 }}>
<Form
ref={formRef}
onChange={setFormValue}
formValue={formValue}
model={model}
>
<TextField name="password"
label="Password"
type="password"
autoComplete="off" />
<TextField
name="verifyPassword"
label="Verify password"
type="password"
autoComplete="off"
/>
</Form>
</div>
)
}
输出:
示例4: 使用rsuite的schema-typed库进行表单验证,打开src文件夹中的App.js文件,编写以下代码。
import React from 'react'
import { Button, ButtonToolbar, Form } from "rsuite"
import { SchemaModel, StringType } from "schema-typed"
import 'rsuite/dist/rsuite.min.css'
export default function App() {
// Saving the form information
// initial value is set to null
const [formValue, setFormValue] = React.useState({
name: "",
email: "",
textarea: ""
})
const formRef = React.useRef()
// Model using schema model to validate
// the data taken in the form
const model = SchemaModel({
name: StringType().isRequired("Enter valid name"),
email: StringType()
.isEmail("Please enter valid email address")
.isRequired("This field is required"),
textarea: StringType()
.isRequired("Describe grievance here")
// Validate the grievance textarea
// with 100 characters only
.maxLength(100)
})
// Handling the form submission
const handleSubmit = () => {
if (!formRef.current.check()) {
console.error("Form error")
return
}
alert("Data collected successfully")
console.log(formValue, "Form data-: ")
}
return (
<div style={{ margin: 30 }}>
{/* handling the form submission */}
<Form
ref={formRef}
model={model}
onChange={setFormValue}
onSubmit={handleSubmit}
fluid>
<Form.Group controlId="name">
<Form.ControlLabel>
Full Name
</Form.ControlLabel>
<Form.Control name="name" />
<Form.HelpText tooltip>
Please enter Full Name
</Form.HelpText>
</Form.Group>
<Form.Group controlId="email">
<Form.ControlLabel>
Email
</Form.ControlLabel>
<Form.Control name="email" />
<Form.HelpText tooltip>
Please enter email
</Form.HelpText>
</Form.Group>
<Form.Group controlId="textarea">
<Form.ControlLabel>
Enter grievance here
</Form.ControlLabel>
<Form.Control name="textarea" rows={5} />
</Form.Group>
<ButtonToolbar>
<Button appearance='primary' type="submit">
Submit
</Button>
</ButtonToolbar>
</Form>
</div>
)
}
输出:
参考: https://rsuitejs.com/components/form-validation/