docs/test: [el-form] add scrollToField docs and test (#3147)

* docs(typography): format docs

* docs(docs): [el-form] add scrollToField method

* test(components): [el-form] add scrollToField test

* destroy mock
This commit is contained in:
三咲智子 2021-09-03 14:13:58 +08:00 committed by GitHub
parent f30bb8853e
commit 80ccfef93c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 1491 additions and 855 deletions

View File

@ -363,6 +363,38 @@ describe('Form', () => {
expect(addressField.validateMessage).toBe('') expect(addressField.validateMessage).toBe('')
}) })
test('scroll to field', () => {
const wrapper = mountForm({
template: `
<div>
<el-form ref="form">
<el-form-item prop="name" ref="formItem">
<el-input></el-input>
</el-form-item>
</el-form>
</div>
`,
data() {
return {
form: {
name: '',
},
}
},
})
const oldScrollIntoView = window.HTMLElement.prototype.scrollIntoView
const scrollIntoViewMock = jest.fn()
window.HTMLElement.prototype.scrollIntoView = function() { scrollIntoViewMock(this) }
const form: any = wrapper.findComponent({ ref: 'form' }).vm
form.scrollToField('name')
expect(scrollIntoViewMock).toHaveBeenCalledWith(wrapper.findComponent({ ref: 'formItem' }).element)
window.HTMLElement.prototype.scrollIntoView = oldScrollIntoView
})
/* /*
test('form item nest', done => { test('form item nest', done => {
const wrapper = mountForm({ const wrapper = mountForm({

View File

@ -25,11 +25,20 @@ It includes all kinds of input items, such as `input`, `select`, `radio` and `ch
</el-form-item> </el-form-item>
<el-form-item label="Activity time"> <el-form-item label="Activity time">
<el-col :span="11"> <el-col :span="11">
<el-date-picker type="date" placeholder="Pick a date" v-model="form.date1" style="width: 100%;"></el-date-picker> <el-date-picker
type="date"
placeholder="Pick a date"
v-model="form.date1"
style="width: 100%;"
></el-date-picker>
</el-col> </el-col>
<el-col class="line" :span="2">-</el-col> <el-col class="line" :span="2">-</el-col>
<el-col :span="11"> <el-col :span="11">
<el-time-picker placeholder="Pick a time" v-model="form.date2" style="width: 100%;"></el-time-picker> <el-time-picker
placeholder="Pick a time"
v-model="form.date2"
style="width: 100%;"
></el-time-picker>
</el-col> </el-col>
</el-form-item> </el-form-item>
<el-form-item label="Instant delivery"> <el-form-item label="Instant delivery">
@ -69,26 +78,28 @@ It includes all kinds of input items, such as `input`, `select`, `radio` and `ch
delivery: false, delivery: false,
type: [], type: [],
resource: '', resource: '',
desc: '' desc: '',
} },
} }
}, },
methods: { methods: {
onSubmit() { onSubmit() {
console.log('submit!'); console.log('submit!')
} },
} },
} }
</script> </script>
``` ```
::: :::
:::tip :::tip
[W3C](https://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2) regulates that [W3C](https://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2) regulates that
> <i>When there is only one single-line text input field in a form, the user agent should accept Enter in that field as a request to submit the form.</i> > <i>When there is only one single-line text input field in a form, the user agent should accept Enter in that field as a request to submit the form.</i>
To prevent this behavior, you can add `@submit.prevent` on `<el-form>`. To prevent this behavior, you can add `@submit.prevent` on `<el-form>`.
::: :::
### Inline form ### Inline form
@ -117,18 +128,19 @@ When the vertical space is limited and the form is relatively simple, you can pu
return { return {
formInline: { formInline: {
user: '', user: '',
region: '' region: '',
} },
} }
}, },
methods: { methods: {
onSubmit() { onSubmit() {
console.log('submit!'); console.log('submit!')
} },
} },
} }
</script> </script>
``` ```
::: :::
### Alignment ### Alignment
@ -144,7 +156,11 @@ Depending on your design, there are several different ways to align your label e
<el-radio-button label="top">Top</el-radio-button> <el-radio-button label="top">Top</el-radio-button>
</el-radio-group> </el-radio-group>
<div style="margin: 20px;"></div> <div style="margin: 20px;"></div>
<el-form :label-position="labelPosition" label-width="100px" :model="formLabelAlign"> <el-form
:label-position="labelPosition"
label-width="100px"
:model="formLabelAlign"
>
<el-form-item label="Name"> <el-form-item label="Name">
<el-input v-model="formLabelAlign.name"></el-input> <el-input v-model="formLabelAlign.name"></el-input>
</el-form-item> </el-form-item>
@ -163,13 +179,14 @@ Depending on your design, there are several different ways to align your label e
formLabelAlign: { formLabelAlign: {
name: '', name: '',
region: '', region: '',
type: '' type: '',
} },
}; }
} },
} }
</script> </script>
``` ```
::: :::
### Validation ### Validation
@ -179,7 +196,13 @@ Form component allows you to verify your data, helping you find and correct erro
:::demo Just add the `rules` attribute for `Form` component, pass validation rules, and set `prop` attribute for `Form-Item` as a specific key that needs to be validated. See more information at [async-validator](https://github.com/yiminghe/async-validator). :::demo Just add the `rules` attribute for `Form` component, pass validation rules, and set `prop` attribute for `Form-Item` as a specific key that needs to be validated. See more information at [async-validator](https://github.com/yiminghe/async-validator).
```html ```html
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm"> <el-form
:model="ruleForm"
:rules="rules"
ref="ruleForm"
label-width="120px"
class="demo-ruleForm"
>
<el-form-item label="Activity name" prop="name"> <el-form-item label="Activity name" prop="name">
<el-input v-model="ruleForm.name"></el-input> <el-input v-model="ruleForm.name"></el-input>
</el-form-item> </el-form-item>
@ -192,13 +215,22 @@ Form component allows you to verify your data, helping you find and correct erro
<el-form-item label="Activity time" required> <el-form-item label="Activity time" required>
<el-col :span="11"> <el-col :span="11">
<el-form-item prop="date1"> <el-form-item prop="date1">
<el-date-picker type="date" placeholder="Pick a date" v-model="ruleForm.date1" style="width: 100%;"></el-date-picker> <el-date-picker
type="date"
placeholder="Pick a date"
v-model="ruleForm.date1"
style="width: 100%;"
></el-date-picker>
</el-form-item> </el-form-item>
</el-col> </el-col>
<el-col class="line" :span="2">-</el-col> <el-col class="line" :span="2">-</el-col>
<el-col :span="11"> <el-col :span="11">
<el-form-item prop="date2"> <el-form-item prop="date2">
<el-time-picker placeholder="Pick a time" v-model="ruleForm.date2" style="width: 100%;"></el-time-picker> <el-time-picker
placeholder="Pick a time"
v-model="ruleForm.date2"
style="width: 100%;"
></el-time-picker>
</el-form-item> </el-form-item>
</el-col> </el-col>
</el-form-item> </el-form-item>
@ -239,52 +271,89 @@ Form component allows you to verify your data, helping you find and correct erro
delivery: false, delivery: false,
type: [], type: [],
resource: '', resource: '',
desc: '' desc: '',
}, },
rules: { rules: {
name: [ name: [
{ required: true, message: 'Please input Activity name', trigger: 'blur' }, {
{ min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' } required: true,
message: 'Please input Activity name',
trigger: 'blur',
},
{
min: 3,
max: 5,
message: 'Length should be 3 to 5',
trigger: 'blur',
},
], ],
region: [ region: [
{ required: true, message: 'Please select Activity zone', trigger: 'change' } {
required: true,
message: 'Please select Activity zone',
trigger: 'change',
},
], ],
date1: [ date1: [
{ type: 'date', required: true, message: 'Please pick a date', trigger: 'change' } {
type: 'date',
required: true,
message: 'Please pick a date',
trigger: 'change',
},
], ],
date2: [ date2: [
{ type: 'date', required: true, message: 'Please pick a time', trigger: 'change' } {
type: 'date',
required: true,
message: 'Please pick a time',
trigger: 'change',
},
], ],
type: [ type: [
{ type: 'array', required: true, message: 'Please select at least one activity type', trigger: 'change' } {
type: 'array',
required: true,
message: 'Please select at least one activity type',
trigger: 'change',
},
], ],
resource: [ resource: [
{ required: true, message: 'Please select activity resource', trigger: 'change' } {
required: true,
message: 'Please select activity resource',
trigger: 'change',
},
], ],
desc: [ desc: [
{ required: true, message: 'Please input activity form', trigger: 'blur' } {
] required: true,
} message: 'Please input activity form',
}; trigger: 'blur',
},
],
},
}
}, },
methods: { methods: {
submitForm(formName) { submitForm(formName) {
this.$refs[formName].validate((valid) => { this.$refs[formName].validate(valid => {
if (valid) { if (valid) {
alert('submit!'); alert('submit!')
} else { } else {
console.log('error submit!!'); console.log('error submit!!')
return false; return false
} }
}); })
}, },
resetForm(formName) { resetForm(formName) {
this.$refs[formName].resetFields(); this.$refs[formName].resetFields()
} },
} },
} }
</script> </script>
``` ```
::: :::
### Custom validation rules ### Custom validation rules
@ -292,13 +361,29 @@ Form component allows you to verify your data, helping you find and correct erro
This example shows how to customize your own validation rules to finish a two-factor password verification. This example shows how to customize your own validation rules to finish a two-factor password verification.
:::demo Here we use `status-icon` to reflect validation result as an icon. :::demo Here we use `status-icon` to reflect validation result as an icon.
```html ```html
<el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm"> <el-form
:model="ruleForm"
status-icon
:rules="rules"
ref="ruleForm"
label-width="120px"
class="demo-ruleForm"
>
<el-form-item label="Password" prop="pass"> <el-form-item label="Password" prop="pass">
<el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input> <el-input
type="password"
v-model="ruleForm.pass"
autocomplete="off"
></el-input>
</el-form-item> </el-form-item>
<el-form-item label="Confirm" prop="checkPass"> <el-form-item label="Confirm" prop="checkPass">
<el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input> <el-input
type="password"
v-model="ruleForm.checkPass"
autocomplete="off"
></el-input>
</el-form-item> </el-form-item>
<el-form-item label="Age" prop="age"> <el-form-item label="Age" prop="age">
<el-input v-model.number="ruleForm.age"></el-input> <el-input v-model.number="ruleForm.age"></el-input>
@ -313,76 +398,71 @@ This example shows how to customize your own validation rules to finish a two-fa
data() { data() {
var checkAge = (rule, value, callback) => { var checkAge = (rule, value, callback) => {
if (!value) { if (!value) {
return callback(new Error('Please input the age')); return callback(new Error('Please input the age'))
} }
setTimeout(() => { setTimeout(() => {
if (!Number.isInteger(value)) { if (!Number.isInteger(value)) {
callback(new Error('Please input digits')); callback(new Error('Please input digits'))
} else { } else {
if (value < 18) { if (value < 18) {
callback(new Error('Age must be greater than 18')); callback(new Error('Age must be greater than 18'))
} else { } else {
callback(); callback()
} }
} }
}, 1000); }, 1000)
}; }
var validatePass = (rule, value, callback) => { var validatePass = (rule, value, callback) => {
if (value === '') { if (value === '') {
callback(new Error('Please input the password')); callback(new Error('Please input the password'))
} else { } else {
if (this.ruleForm.checkPass !== '') { if (this.ruleForm.checkPass !== '') {
this.$refs.ruleForm.validateField('checkPass'); this.$refs.ruleForm.validateField('checkPass')
} }
callback(); callback()
} }
}; }
var validatePass2 = (rule, value, callback) => { var validatePass2 = (rule, value, callback) => {
if (value === '') { if (value === '') {
callback(new Error('Please input the password again')); callback(new Error('Please input the password again'))
} else if (value !== this.ruleForm.pass) { } else if (value !== this.ruleForm.pass) {
callback(new Error('Two inputs don\'t match!')); callback(new Error("Two inputs don't match!"))
} else { } else {
callback(); callback()
} }
}; }
return { return {
ruleForm: { ruleForm: {
pass: '', pass: '',
checkPass: '', checkPass: '',
age: '' age: '',
}, },
rules: { rules: {
pass: [ pass: [{ validator: validatePass, trigger: 'blur' }],
{ validator: validatePass, trigger: 'blur' } checkPass: [{ validator: validatePass2, trigger: 'blur' }],
], age: [{ validator: checkAge, trigger: 'blur' }],
checkPass: [ },
{ validator: validatePass2, trigger: 'blur' } }
],
age: [
{ validator: checkAge, trigger: 'blur' }
]
}
};
}, },
methods: { methods: {
submitForm(formName) { submitForm(formName) {
this.$refs[formName].validate((valid) => { this.$refs[formName].validate(valid => {
if (valid) { if (valid) {
alert('submit!'); alert('submit!')
} else { } else {
console.log('error submit!!'); console.log('error submit!!')
return false; return false
} }
}); })
}, },
resetForm(formName) { resetForm(formName) {
this.$refs[formName].resetFields(); this.$refs[formName].resetFields()
} },
} },
} }
</script> </script>
``` ```
::: :::
:::tip :::tip
@ -394,7 +474,12 @@ Custom validate callback function must be called. See more advanced usage at [as
:::demo In addition to passing all validation rules at once on the form component, you can also pass the validation rules or delete rules on a single form field dynamically. :::demo In addition to passing all validation rules at once on the form component, you can also pass the validation rules or delete rules on a single form field dynamically.
```html ```html
<el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="120px" class="demo-dynamic"> <el-form
:model="dynamicValidateForm"
ref="dynamicValidateForm"
label-width="120px"
class="demo-dynamic"
>
<el-form-item <el-form-item
prop="email" prop="email"
label="Email" label="Email"
@ -414,10 +499,13 @@ Custom validate callback function must be called. See more advanced usage at [as
required: true, message: 'domain can not be null', trigger: 'blur' required: true, message: 'domain can not be null', trigger: 'blur'
}" }"
> >
<el-input v-model="domain.value"></el-input><el-button @click.prevent="removeDomain(domain)">Delete</el-button> <el-input v-model="domain.value"></el-input
><el-button @click.prevent="removeDomain(domain)">Delete</el-button>
</el-form-item> </el-form-item>
<el-form-item> <el-form-item>
<el-button type="primary" @click="submitForm('dynamicValidateForm')">Submit</el-button> <el-button type="primary" @click="submitForm('dynamicValidateForm')"
>Submit</el-button
>
<el-button @click="addDomain">New domain</el-button> <el-button @click="addDomain">New domain</el-button>
<el-button @click="resetForm('dynamicValidateForm')">Reset</el-button> <el-button @click="resetForm('dynamicValidateForm')">Reset</el-button>
</el-form-item> </el-form-item>
@ -427,51 +515,60 @@ Custom validate callback function must be called. See more advanced usage at [as
data() { data() {
return { return {
dynamicValidateForm: { dynamicValidateForm: {
domains: [{ domains: [
key: 1, {
value: '' key: 1,
}], value: '',
email: '' },
} ],
}; email: '',
},
}
}, },
methods: { methods: {
submitForm(formName) { submitForm(formName) {
this.$refs[formName].validate((valid) => { this.$refs[formName].validate(valid => {
if (valid) { if (valid) {
alert('submit!'); alert('submit!')
} else { } else {
console.log('error submit!!'); console.log('error submit!!')
return false; return false
} }
}); })
}, },
resetForm(formName) { resetForm(formName) {
this.$refs[formName].resetFields(); this.$refs[formName].resetFields()
}, },
removeDomain(item) { removeDomain(item) {
var index = this.dynamicValidateForm.domains.indexOf(item); var index = this.dynamicValidateForm.domains.indexOf(item)
if (index !== -1) { if (index !== -1) {
this.dynamicValidateForm.domains.splice(index, 1); this.dynamicValidateForm.domains.splice(index, 1)
} }
}, },
addDomain() { addDomain() {
this.dynamicValidateForm.domains.push({ this.dynamicValidateForm.domains.push({
key: Date.now(), key: Date.now(),
value: '' value: '',
}); })
} },
} },
} }
</script> </script>
``` ```
::: :::
### Number Validate ### Number Validate
:::demo Number Validate need a `.number` modifier added on the input `v-model` bindingit's used to transform the string value to the number which is provided by Vuejs. :::demo Number Validate need a `.number` modifier added on the input `v-model` bindingit's used to transform the string value to the number which is provided by Vuejs.
```html ```html
<el-form :model="numberValidateForm" ref="numberValidateForm" label-width="100px" class="demo-ruleForm"> <el-form
:model="numberValidateForm"
ref="numberValidateForm"
label-width="100px"
class="demo-ruleForm"
>
<el-form-item <el-form-item
label="age" label="age"
prop="age" prop="age"
@ -480,10 +577,16 @@ Custom validate callback function must be called. See more advanced usage at [as
{ type: 'number', message: 'age must be a number'} { type: 'number', message: 'age must be a number'}
]" ]"
> >
<el-input type="age" v-model.number="numberValidateForm.age" autocomplete="off"></el-input> <el-input
type="age"
v-model.number="numberValidateForm.age"
autocomplete="off"
></el-input>
</el-form-item> </el-form-item>
<el-form-item> <el-form-item>
<el-button type="primary" @click="submitForm('numberValidateForm')">Submit</el-button> <el-button type="primary" @click="submitForm('numberValidateForm')"
>Submit</el-button
>
<el-button @click="resetForm('numberValidateForm')">Reset</el-button> <el-button @click="resetForm('numberValidateForm')">Reset</el-button>
</el-form-item> </el-form-item>
</el-form> </el-form>
@ -492,28 +595,29 @@ Custom validate callback function must be called. See more advanced usage at [as
data() { data() {
return { return {
numberValidateForm: { numberValidateForm: {
age: '' age: '',
} },
}; }
}, },
methods: { methods: {
submitForm(formName) { submitForm(formName) {
this.$refs[formName].validate((valid) => { this.$refs[formName].validate(valid => {
if (valid) { if (valid) {
alert('submit!'); alert('submit!')
} else { } else {
console.log('error submit!!'); console.log('error submit!!')
return false; return false
} }
}); })
}, },
resetForm(formName) { resetForm(formName) {
this.$refs[formName].resetFields(); this.$refs[formName].resetFields()
} },
} },
} }
</script> </script>
``` ```
::: :::
:::tip :::tip
@ -525,6 +629,7 @@ When an `el-form-item` is nested in another `el-form-item`, its label width will
All components in a Form inherit their `size` attribute from that Form. Similarly, FormItem also has a `size` attribute. All components in a Form inherit their `size` attribute from that Form. Similarly, FormItem also has a `size` attribute.
:::demo Still you can fine tune each component's `size` if you don't want that component to inherit its size from From or FormIten. :::demo Still you can fine tune each component's `size` if you don't want that component to inherit its size from From or FormIten.
```html ```html
<el-form ref="form" :model="sizeForm" label-width="120px" size="mini"> <el-form ref="form" :model="sizeForm" label-width="120px" size="mini">
<el-form-item label="Activity name"> <el-form-item label="Activity name">
@ -538,17 +643,32 @@ All components in a Form inherit their `size` attribute from that Form. Similarl
</el-form-item> </el-form-item>
<el-form-item label="Activity time"> <el-form-item label="Activity time">
<el-col :span="11"> <el-col :span="11">
<el-date-picker type="date" placeholder="Pick a date" v-model="sizeForm.date1" style="width: 100%;"></el-date-picker> <el-date-picker
type="date"
placeholder="Pick a date"
v-model="sizeForm.date1"
style="width: 100%;"
></el-date-picker>
</el-col> </el-col>
<el-col class="line" :span="2">-</el-col> <el-col class="line" :span="2">-</el-col>
<el-col :span="11"> <el-col :span="11">
<el-time-picker placeholder="Pick a time" v-model="sizeForm.date2" style="width: 100%;"></el-time-picker> <el-time-picker
placeholder="Pick a time"
v-model="sizeForm.date2"
style="width: 100%;"
></el-time-picker>
</el-col> </el-col>
</el-form-item> </el-form-item>
<el-form-item label="Activity type"> <el-form-item label="Activity type">
<el-checkbox-group v-model="sizeForm.type"> <el-checkbox-group v-model="sizeForm.type">
<el-checkbox-button label="Online activities" name="type"></el-checkbox-button> <el-checkbox-button
<el-checkbox-button label="Promotion activities" name="type"></el-checkbox-button> label="Online activities"
name="type"
></el-checkbox-button>
<el-checkbox-button
label="Promotion activities"
name="type"
></el-checkbox-button>
</el-checkbox-group> </el-checkbox-group>
</el-form-item> </el-form-item>
<el-form-item label="Resources"> <el-form-item label="Resources">
@ -575,81 +695,86 @@ All components in a Form inherit their `size` attribute from that Form. Similarl
delivery: false, delivery: false,
type: [], type: [],
resource: '', resource: '',
desc: '' desc: '',
} },
}; }
}, },
methods: { methods: {
onSubmit() { onSubmit() {
console.log('submit!'); console.log('submit!')
} },
} },
}; }
</script> </script>
``` ```
::: :::
### Form Attributes ### Form Attributes
| Attribute | Description | Type | Accepted Values | Default | | Attribute | Description | Type | Accepted Values | Default |
| ---- | ----| ---- | ---- | ---- | | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------- | --------------- | --------------------- | ------- |
| model| data of form component | object | — | — | | model | data of form component | object | — | — |
| rules | validation rules of form | object | — | — | | rules | validation rules of form | object | — | — |
| inline | whether the form is inline | boolean | — | false | | inline | whether the form is inline | boolean | — | false |
| label-position | position of label. If set to 'left' or 'right', `label-width` prop is also required | string | left / right / top | right | | label-position | position of label. If set to 'left' or 'right', `label-width` prop is also required | string | left / right / top | right |
| label-width | width of label, e.g. '50px'. All its direct child form items will inherit this value. Width `auto` is supported. | string / number | — | — | | label-width | width of label, e.g. '50px'. All its direct child form items will inherit this value. Width `auto` is supported. | string / number | — | — |
| label-suffix | suffix of the label | string | — | — | | label-suffix | suffix of the label | string | — | — |
| hide-required-asterisk | whether required fields should have a red asterisk (star) beside their labels | boolean | — | false | | hide-required-asterisk | whether required fields should have a red asterisk (star) beside their labels | boolean | — | false |
| show-message | whether to show the error message | boolean | — | true | | show-message | whether to show the error message | boolean | — | true |
| inline-message | whether to display the error message inline with the form item | boolean | — | false | | inline-message | whether to display the error message inline with the form item | boolean | — | false |
| status-icon | whether to display an icon indicating the validation result | boolean | — | false | | status-icon | whether to display an icon indicating the validation result | boolean | — | false |
| validate-on-rule-change | whether to trigger validation when the `rules` prop is changed | boolean | — | true | | validate-on-rule-change | whether to trigger validation when the `rules` prop is changed | boolean | — | true |
| size | control the size of components in this form | string | medium / small / mini | — | | size | control the size of components in this form | string | medium / small / mini | — |
| disabled | whether to disabled all components in this form. If set to true, it cannot be overridden by its inner components' `disabled` prop | boolean | — | false | | disabled | whether to disabled all components in this form. If set to true, it cannot be overridden by its inner components' `disabled` prop | boolean | — | false |
### Form Methods ### Form Methods
| Method | Description | Parameters | | Method | Description | Parameters |
| ---- | ---- | ---- | | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
| validate | validate the whole form. Takes a callback as a param. After validation, the callback will be executed with two params: a boolean indicating if the validation has passed, and an object containing all fields that fail the validation. Returns a promise if callback is omitted | Function(callback: Function(boolean, object)) | | validate | validate the whole form. Takes a callback as a param. After validation, the callback will be executed with two params: a boolean indicating if the validation has passed, and an object containing all fields that fail the validation. Returns a promise if callback is omitted | Function(callback: Function(boolean, object)) |
| validateField | validate one or several form items | Function(props: string \| array, callback: Function(errorMessage: string)) | | validateField | validate one or several form items | Function(props: string \| array, callback: Function(errorMessage: string)) |
| resetFields | reset all the fields and remove validation result | — | | resetFields | reset all the fields and remove validation result | — |
| clearValidate | clear validation message for certain fields. The parameter is prop name or an array of prop names of the form items whose validation messages will be removed. When omitted, all fields' validation messages will be cleared | Function(props: string \| array) | | scrollToField | Scroll to the specified form field | Function(prop: string) |
| clearValidate | clear validation message for certain fields. The parameter is prop name or an array of prop names of the form items whose validation messages will be removed. When omitted, all fields' validation messages will be cleared | Function(props: string \| array) |
### Form Events ### Form Events
| Event Name | Description | Parameters |
|----------- |------------ |----------- | | Event Name | Description | Parameters |
| ---------- | --------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| validate | triggers after a form item is validated | prop name of the form item being validated, whether validation is passed and the error message if not | | validate | triggers after a form item is validated | prop name of the form item being validated, whether validation is passed and the error message if not |
### Form-Item Attributes ### Form-Item Attributes
| Attribute | Description | Type | Accepted Values | Default | | Attribute | Description | Type | Accepted Values | Default |
| ---- | ----| ---- | ---- | ---- | | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | --------------- | ----------------------------------- | ------- |
| prop | a key of `model`. In the use of validate and resetFields method, the attribute is required | string | keys of model that passed to `form` | | prop | a key of `model`. In the use of validate and resetFields method, the attribute is required | string | keys of model that passed to `form` |
| label | label | string | — | — | | label | label | string | — | — |
| label-width | width of label, e.g. '50px'. Width `auto` is supported. | string / number | — | — | | label-width | width of label, e.g. '50px'. Width `auto` is supported. | string / number | — | — |
| required | whether the field is required or not, will be determined by validation rules if omitted | boolean | — | false | | required | whether the field is required or not, will be determined by validation rules if omitted | boolean | — | false |
| rules | validation rules of form, see the following table, more advanced usage at [async-validator](https://github.com/yiminghe/async-validator) | object / array | — | — | | rules | validation rules of form, see the following table, more advanced usage at [async-validator](https://github.com/yiminghe/async-validator) | object / array | — | — |
| error | field error message, set its value and the field will validate error and show this message immediately | string | — | — | | error | field error message, set its value and the field will validate error and show this message immediately | string | — | — |
| show-message | whether to show the error message | boolean | — | true | | show-message | whether to show the error message | boolean | — | true |
| inline-message | inline style validate message | boolean | — | false | | inline-message | inline style validate message | boolean | — | false |
| size | control the size of components in this form-item | string | medium / small / mini | — | | size | control the size of components in this form-item | string | medium / small / mini | — |
### Rules ### Rules
| Attribute | Description | Type | Accepted Values | Default |
| -------- | ----------------- | ------ | ---- | ---- | | Attribute | Description | Type | Accepted Values | Default |
| trigger | how the validator is triggered | string | blur / change | — | | --------- | ------------------------------ | ------ | --------------- | ------- |
| trigger | how the validator is triggered | string | blur / change | — |
### Form-Item Slots ### Form-Item Slots
| Name | Description |
|------|--------| | Name | Description |
| — | content of Form Item | | ----- | ------------------------------------------------------------------------------ |
| label | Custom content to display on label. The scope parameter is { label } | | — | content of Form Item |
| error | Custom content to display validation message. The scope parameter is { error } | | label | Custom content to display on label. The scope parameter is { label } |
| error | Custom content to display validation message. The scope parameter is { error } |
### Form-Item Methods ### Form-Item Methods
| Method | Description | Parameters | | Method | Description | Parameters |
| ---- | ---- | ---- | | ------------- | ------------------------------------------------ | ---------- |
| resetField | reset current field and remove validation result | — | | resetField | reset current field and remove validation result | — |
| clearValidate | remove validation status of the field | — | | clearValidate | remove validation status of the field | — |

View File

@ -25,11 +25,20 @@ Incluye todo tipo de entradas, tales como `input`, `select`, `radio` y `checkbox
</el-form-item> </el-form-item>
<el-form-item label="Activity time"> <el-form-item label="Activity time">
<el-col :span="11"> <el-col :span="11">
<el-date-picker type="date" placeholder="Pick a date" v-model="form.date1" style="width: 100%;"></el-date-picker> <el-date-picker
type="date"
placeholder="Pick a date"
v-model="form.date1"
style="width: 100%;"
></el-date-picker>
</el-col> </el-col>
<el-col class="line" :span="2">-</el-col> <el-col class="line" :span="2">-</el-col>
<el-col :span="11"> <el-col :span="11">
<el-time-picker placeholder="Pick a time" v-model="form.date2" style="width: 100%;"></el-time-picker> <el-time-picker
placeholder="Pick a time"
v-model="form.date2"
style="width: 100%;"
></el-time-picker>
</el-col> </el-col>
</el-form-item> </el-form-item>
<el-form-item label="Instant delivery"> <el-form-item label="Instant delivery">
@ -69,15 +78,15 @@ Incluye todo tipo de entradas, tales como `input`, `select`, `radio` y `checkbox
delivery: false, delivery: false,
type: [], type: [],
resource: '', resource: '',
desc: '' desc: '',
} },
} }
}, },
methods: { methods: {
onSubmit() { onSubmit() {
console.log('submit!'); console.log('submit!')
} },
} },
} }
</script> </script>
``` ```
@ -119,15 +128,15 @@ Cuando el espacio vertical es limitado y la forma es relativamente simple, puede
return { return {
formInline: { formInline: {
user: '', user: '',
region: '' region: '',
} },
} }
}, },
methods: { methods: {
onSubmit() { onSubmit() {
console.log('submit!'); console.log('submit!')
} },
} },
} }
</script> </script>
``` ```
@ -147,7 +156,11 @@ Dependiendo de su diseño, hay varias maneras diferentes de alinear el elemento
<el-radio-button label="top">Top</el-radio-button> <el-radio-button label="top">Top</el-radio-button>
</el-radio-group> </el-radio-group>
<div style="margin: 20px;"></div> <div style="margin: 20px;"></div>
<el-form :label-position="labelPosition" label-width="100px" :model="formLabelAlign"> <el-form
:label-position="labelPosition"
label-width="100px"
:model="formLabelAlign"
>
<el-form-item label="Name"> <el-form-item label="Name">
<el-input v-model="formLabelAlign.name"></el-input> <el-input v-model="formLabelAlign.name"></el-input>
</el-form-item> </el-form-item>
@ -166,10 +179,10 @@ Dependiendo de su diseño, hay varias maneras diferentes de alinear el elemento
formLabelAlign: { formLabelAlign: {
name: '', name: '',
region: '', region: '',
type: '' type: '',
} },
}; }
} },
} }
</script> </script>
``` ```
@ -183,7 +196,13 @@ El componente `form` le permite verificar sus datos, ayudándole a encontrar y c
:::demo Sólo tiene que añadir el atributo `rules` en el componente `Form`, pasar las reglas de validación y establecer el atributo `prop` para `Form-Item` como una clave específica que necesita ser validada. Ver más información en [async-validator](https://github.com/yiminghe/async-validator). :::demo Sólo tiene que añadir el atributo `rules` en el componente `Form`, pasar las reglas de validación y establecer el atributo `prop` para `Form-Item` como una clave específica que necesita ser validada. Ver más información en [async-validator](https://github.com/yiminghe/async-validator).
```html ```html
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm"> <el-form
:model="ruleForm"
:rules="rules"
ref="ruleForm"
label-width="120px"
class="demo-ruleForm"
>
<el-form-item label="Activity name" prop="name"> <el-form-item label="Activity name" prop="name">
<el-input v-model="ruleForm.name"></el-input> <el-input v-model="ruleForm.name"></el-input>
</el-form-item> </el-form-item>
@ -196,13 +215,22 @@ El componente `form` le permite verificar sus datos, ayudándole a encontrar y c
<el-form-item label="Activity time" required> <el-form-item label="Activity time" required>
<el-col :span="11"> <el-col :span="11">
<el-form-item prop="date1"> <el-form-item prop="date1">
<el-date-picker type="date" placeholder="Pick a date" v-model="ruleForm.date1" style="width: 100%;"></el-date-picker> <el-date-picker
type="date"
placeholder="Pick a date"
v-model="ruleForm.date1"
style="width: 100%;"
></el-date-picker>
</el-form-item> </el-form-item>
</el-col> </el-col>
<el-col class="line" :span="2">-</el-col> <el-col class="line" :span="2">-</el-col>
<el-col :span="11"> <el-col :span="11">
<el-form-item prop="date2"> <el-form-item prop="date2">
<el-time-picker placeholder="Pick a time" v-model="ruleForm.date2" style="width: 100%;"></el-time-picker> <el-time-picker
placeholder="Pick a time"
v-model="ruleForm.date2"
style="width: 100%;"
></el-time-picker>
</el-form-item> </el-form-item>
</el-col> </el-col>
</el-form-item> </el-form-item>
@ -243,49 +271,85 @@ El componente `form` le permite verificar sus datos, ayudándole a encontrar y c
delivery: false, delivery: false,
type: [], type: [],
resource: '', resource: '',
desc: '' desc: '',
}, },
rules: { rules: {
name: [ name: [
{ required: true, message: 'Please input Activity name', trigger: 'blur' }, {
{ min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' } required: true,
message: 'Please input Activity name',
trigger: 'blur',
},
{
min: 3,
max: 5,
message: 'Length should be 3 to 5',
trigger: 'blur',
},
], ],
region: [ region: [
{ required: true, message: 'Please select Activity zone', trigger: 'change' } {
required: true,
message: 'Please select Activity zone',
trigger: 'change',
},
], ],
date1: [ date1: [
{ type: 'date', required: true, message: 'Please pick a date', trigger: 'change' } {
type: 'date',
required: true,
message: 'Please pick a date',
trigger: 'change',
},
], ],
date2: [ date2: [
{ type: 'date', required: true, message: 'Please pick a time', trigger: 'change' } {
type: 'date',
required: true,
message: 'Please pick a time',
trigger: 'change',
},
], ],
type: [ type: [
{ type: 'array', required: true, message: 'Please select at least one activity type', trigger: 'change' } {
type: 'array',
required: true,
message: 'Please select at least one activity type',
trigger: 'change',
},
], ],
resource: [ resource: [
{ required: true, message: 'Please select activity resource', trigger: 'change' } {
required: true,
message: 'Please select activity resource',
trigger: 'change',
},
], ],
desc: [ desc: [
{ required: true, message: 'Please input activity form', trigger: 'blur' } {
] required: true,
} message: 'Please input activity form',
}; trigger: 'blur',
},
],
},
}
}, },
methods: { methods: {
submitForm(formName) { submitForm(formName) {
this.$refs[formName].validate((valid) => { this.$refs[formName].validate(valid => {
if (valid) { if (valid) {
alert('submit!'); alert('submit!')
} else { } else {
console.log('error submit!!'); console.log('error submit!!')
return false; return false
} }
}); })
}, },
resetForm(formName) { resetForm(formName) {
this.$refs[formName].resetFields(); this.$refs[formName].resetFields()
} },
} },
} }
</script> </script>
``` ```
@ -299,12 +363,27 @@ Este ejemplo muestra cómo personalizar sus propias reglas de validación para f
:::demo Aquí utilizamos el `status-icon` para reflejar el resultado de la validación como un icono. :::demo Aquí utilizamos el `status-icon` para reflejar el resultado de la validación como un icono.
```html ```html
<el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm"> <el-form
:model="ruleForm"
status-icon
:rules="rules"
ref="ruleForm"
label-width="120px"
class="demo-ruleForm"
>
<el-form-item label="Password" prop="pass"> <el-form-item label="Password" prop="pass">
<el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input> <el-input
type="password"
v-model="ruleForm.pass"
autocomplete="off"
></el-input>
</el-form-item> </el-form-item>
<el-form-item label="Confirm" prop="checkPass"> <el-form-item label="Confirm" prop="checkPass">
<el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input> <el-input
type="password"
v-model="ruleForm.checkPass"
autocomplete="off"
></el-input>
</el-form-item> </el-form-item>
<el-form-item label="Age" prop="age"> <el-form-item label="Age" prop="age">
<el-input v-model.number="ruleForm.age"></el-input> <el-input v-model.number="ruleForm.age"></el-input>
@ -319,73 +398,67 @@ Este ejemplo muestra cómo personalizar sus propias reglas de validación para f
data() { data() {
var checkAge = (rule, value, callback) => { var checkAge = (rule, value, callback) => {
if (!value) { if (!value) {
return callback(new Error('Please input the age')); return callback(new Error('Please input the age'))
} }
setTimeout(() => { setTimeout(() => {
if (!Number.isInteger(value)) { if (!Number.isInteger(value)) {
callback(new Error('Please input digits')); callback(new Error('Please input digits'))
} else { } else {
if (value < 18) { if (value < 18) {
callback(new Error('Age must be greater than 18')); callback(new Error('Age must be greater than 18'))
} else { } else {
callback(); callback()
} }
} }
}, 1000); }, 1000)
}; }
var validatePass = (rule, value, callback) => { var validatePass = (rule, value, callback) => {
if (value === '') { if (value === '') {
callback(new Error('Please input the password')); callback(new Error('Please input the password'))
} else { } else {
if (this.ruleForm.checkPass !== '') { if (this.ruleForm.checkPass !== '') {
this.$refs.ruleForm.validateField('checkPass'); this.$refs.ruleForm.validateField('checkPass')
} }
callback(); callback()
} }
}; }
var validatePass2 = (rule, value, callback) => { var validatePass2 = (rule, value, callback) => {
if (value === '') { if (value === '') {
callback(new Error('Please input the password again')); callback(new Error('Please input the password again'))
} else if (value !== this.ruleForm.pass) { } else if (value !== this.ruleForm.pass) {
callback(new Error('Two inputs don\'t match!')); callback(new Error("Two inputs don't match!"))
} else { } else {
callback(); callback()
} }
}; }
return { return {
ruleForm: { ruleForm: {
pass: '', pass: '',
checkPass: '', checkPass: '',
age: '' age: '',
}, },
rules: { rules: {
pass: [ pass: [{ validator: validatePass, trigger: 'blur' }],
{ validator: validatePass, trigger: 'blur' } checkPass: [{ validator: validatePass2, trigger: 'blur' }],
], age: [{ validator: checkAge, trigger: 'blur' }],
checkPass: [ },
{ validator: validatePass2, trigger: 'blur' } }
],
age: [
{ validator: checkAge, trigger: 'blur' }
]
}
};
}, },
methods: { methods: {
submitForm(formName) { submitForm(formName) {
this.$refs[formName].validate((valid) => { this.$refs[formName].validate(valid => {
if (valid) { if (valid) {
alert('submit!'); alert('submit!')
} else { } else {
console.log('error submit!!'); console.log('error submit!!')
return false; return false
} }
}); })
}, },
resetForm(formName) { resetForm(formName) {
this.$refs[formName].resetFields(); this.$refs[formName].resetFields()
} },
} },
} }
</script> </script>
``` ```
@ -401,7 +474,12 @@ Se debe llamar a la función de validación de llamada de retorno personalizada.
:::demo Además de pasar todas las reglas de validación al mismo tiempo en el componente `form`, también puede pasar las reglas de validación o borrar reglas en un único campo de formulario de forma dinámica. :::demo Además de pasar todas las reglas de validación al mismo tiempo en el componente `form`, también puede pasar las reglas de validación o borrar reglas en un único campo de formulario de forma dinámica.
```html ```html
<el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="120px" class="demo-dynamic"> <el-form
:model="dynamicValidateForm"
ref="dynamicValidateForm"
label-width="120px"
class="demo-dynamic"
>
<el-form-item <el-form-item
prop="email" prop="email"
label="Email" label="Email"
@ -421,10 +499,13 @@ Se debe llamar a la función de validación de llamada de retorno personalizada.
required: true, message: 'domain can not be null', trigger: 'blur' required: true, message: 'domain can not be null', trigger: 'blur'
}" }"
> >
<el-input v-model="domain.value"></el-input><el-button @click.prevent="removeDomain(domain)">Delete</el-button> <el-input v-model="domain.value"></el-input
><el-button @click.prevent="removeDomain(domain)">Delete</el-button>
</el-form-item> </el-form-item>
<el-form-item> <el-form-item>
<el-button type="primary" @click="submitForm('dynamicValidateForm')">Submit</el-button> <el-button type="primary" @click="submitForm('dynamicValidateForm')"
>Submit</el-button
>
<el-button @click="addDomain">New domain</el-button> <el-button @click="addDomain">New domain</el-button>
<el-button @click="resetForm('dynamicValidateForm')">Reset</el-button> <el-button @click="resetForm('dynamicValidateForm')">Reset</el-button>
</el-form-item> </el-form-item>
@ -434,41 +515,43 @@ Se debe llamar a la función de validación de llamada de retorno personalizada.
data() { data() {
return { return {
dynamicValidateForm: { dynamicValidateForm: {
domains: [{ domains: [
key: 1, {
value: '' key: 1,
}], value: '',
email: '' },
} ],
}; email: '',
},
}
}, },
methods: { methods: {
submitForm(formName) { submitForm(formName) {
this.$refs[formName].validate((valid) => { this.$refs[formName].validate(valid => {
if (valid) { if (valid) {
alert('submit!'); alert('submit!')
} else { } else {
console.log('error submit!!'); console.log('error submit!!')
return false; return false
} }
}); })
}, },
resetForm(formName) { resetForm(formName) {
this.$refs[formName].resetFields(); this.$refs[formName].resetFields()
}, },
removeDomain(item) { removeDomain(item) {
var index = this.dynamicValidateForm.domains.indexOf(item); var index = this.dynamicValidateForm.domains.indexOf(item)
if (index !== -1) { if (index !== -1) {
this.dynamicValidateForm.domains.splice(index, 1); this.dynamicValidateForm.domains.splice(index, 1)
} }
}, },
addDomain() { addDomain() {
this.dynamicValidateForm.domains.push({ this.dynamicValidateForm.domains.push({
key: Date.now(), key: Date.now(),
value: '' value: '',
}); })
} },
} },
} }
</script> </script>
``` ```
@ -480,7 +563,12 @@ Se debe llamar a la función de validación de llamada de retorno personalizada.
:::demo La validación numérica necesita un modificador `.number` añadido en el enlace `v-model` de entrada, sirve para transformar el valor de la cadena al número proporcionado por Vuejs. :::demo La validación numérica necesita un modificador `.number` añadido en el enlace `v-model` de entrada, sirve para transformar el valor de la cadena al número proporcionado por Vuejs.
```html ```html
<el-form :model="numberValidateForm" ref="numberValidateForm" label-width="100px" class="demo-ruleForm"> <el-form
:model="numberValidateForm"
ref="numberValidateForm"
label-width="100px"
class="demo-ruleForm"
>
<el-form-item <el-form-item
label="age" label="age"
prop="age" prop="age"
@ -489,10 +577,16 @@ Se debe llamar a la función de validación de llamada de retorno personalizada.
{ type: 'number', message: 'age must be a number'} { type: 'number', message: 'age must be a number'}
]" ]"
> >
<el-input type="age" v-model.number="numberValidateForm.age" autocomplete="off"></el-input> <el-input
type="age"
v-model.number="numberValidateForm.age"
autocomplete="off"
></el-input>
</el-form-item> </el-form-item>
<el-form-item> <el-form-item>
<el-button type="primary" @click="submitForm('numberValidateForm')">Submit</el-button> <el-button type="primary" @click="submitForm('numberValidateForm')"
>Submit</el-button
>
<el-button @click="resetForm('numberValidateForm')">Reset</el-button> <el-button @click="resetForm('numberValidateForm')">Reset</el-button>
</el-form-item> </el-form-item>
</el-form> </el-form>
@ -501,25 +595,25 @@ Se debe llamar a la función de validación de llamada de retorno personalizada.
data() { data() {
return { return {
numberValidateForm: { numberValidateForm: {
age: '' age: '',
} },
}; }
}, },
methods: { methods: {
submitForm(formName) { submitForm(formName) {
this.$refs[formName].validate((valid) => { this.$refs[formName].validate(valid => {
if (valid) { if (valid) {
alert('submit!'); alert('submit!')
} else { } else {
console.log('error submit!!'); console.log('error submit!!')
return false; return false
} }
}); })
}, },
resetForm(formName) { resetForm(formName) {
this.$refs[formName].resetFields(); this.$refs[formName].resetFields()
} },
} },
} }
</script> </script>
``` ```
@ -551,17 +645,32 @@ Todos los componentes de un formulario heredan su atributo `size`. De manera sim
</el-form-item> </el-form-item>
<el-form-item label="Activity time"> <el-form-item label="Activity time">
<el-col :span="11"> <el-col :span="11">
<el-date-picker type="date" placeholder="Pick a date" v-model="sizeForm.date1" style="width: 100%;"></el-date-picker> <el-date-picker
type="date"
placeholder="Pick a date"
v-model="sizeForm.date1"
style="width: 100%;"
></el-date-picker>
</el-col> </el-col>
<el-col class="line" :span="2">-</el-col> <el-col class="line" :span="2">-</el-col>
<el-col :span="11"> <el-col :span="11">
<el-time-picker placeholder="Pick a time" v-model="sizeForm.date2" style="width: 100%;"></el-time-picker> <el-time-picker
placeholder="Pick a time"
v-model="sizeForm.date2"
style="width: 100%;"
></el-time-picker>
</el-col> </el-col>
</el-form-item> </el-form-item>
<el-form-item label="Activity type"> <el-form-item label="Activity type">
<el-checkbox-group v-model="sizeForm.type"> <el-checkbox-group v-model="sizeForm.type">
<el-checkbox-button label="Online activities" name="type"></el-checkbox-button> <el-checkbox-button
<el-checkbox-button label="Promotion activities" name="type"></el-checkbox-button> label="Online activities"
name="type"
></el-checkbox-button>
<el-checkbox-button
label="Promotion activities"
name="type"
></el-checkbox-button>
</el-checkbox-group> </el-checkbox-group>
</el-form-item> </el-form-item>
<el-form-item label="Resources"> <el-form-item label="Resources">
@ -588,16 +697,16 @@ Todos los componentes de un formulario heredan su atributo `size`. De manera sim
delivery: false, delivery: false,
type: [], type: [],
resource: '', resource: '',
desc: '' desc: '',
} },
}; }
}, },
methods: { methods: {
onSubmit() { onSubmit() {
console.log('submit!'); console.log('submit!')
} },
} },
}; }
</script> </script>
``` ```
@ -605,64 +714,65 @@ Todos los componentes de un formulario heredan su atributo `size`. De manera sim
### Form Atributos ### Form Atributos
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto | | Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| ----------------------- | ---------------------------------------- | ------- | --------------------- | ----------- | | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | --------------------- | ----------- |
| model | Datos del componente | object | — | — | | model | Datos del componente | object | — | — |
| rules | Reglas de validación | object | — | — | | rules | Reglas de validación | object | — | — |
| inline | Si el form es inline | boolean | — | false | | inline | Si el form es inline | boolean | — | false |
| label-position | Posición de la etiqueta | string | left / right / top | right | | label-position | Posición de la etiqueta | string | left / right / top | right |
| label-width | anchura de la etiqueta, por ejemplo, "50px". Todos sus elementos de formulario hijo directo heredarán este valor. El valor `auto` está soportado. | string / number | — | — | | label-width | anchura de la etiqueta, por ejemplo, "50px". Todos sus elementos de formulario hijo directo heredarán este valor. El valor `auto` está soportado. | string / number | — | — |
| label-suffix | sufijo de la etiqueta | string | — | — | | label-suffix | sufijo de la etiqueta | string | — | — |
| hide-required-asterisk | si los campos obligatorios deben tener un asterisco rojo (estrella) al lado de sus etiquetas | boolean | — | false | | hide-required-asterisk | si los campos obligatorios deben tener un asterisco rojo (estrella) al lado de sus etiquetas | boolean | — | false |
| show-message | si mostrar o no el mensaje de error | boolean | — | true | | show-message | si mostrar o no el mensaje de error | boolean | — | true |
| inline-message | si desea visualizar el mensaje de error inline con la posición del form item | boolean | — | false | | inline-message | si desea visualizar el mensaje de error inline con la posición del form item | boolean | — | false |
| status-icon | si desea visualizar un icono que indique el resultado de la validación | boolean | — | false | | status-icon | si desea visualizar un icono que indique el resultado de la validación | boolean | — | false |
| validate-on-rule-change | si se dispara la validación cuando el prop `rules` cambia | boolean | — | true | | validate-on-rule-change | si se dispara la validación cuando el prop `rules` cambia | boolean | — | true |
| size | el tamaño de los componentes en este form | string | medium / small / mini | — | | size | el tamaño de los componentes en este form | string | medium / small / mini | — |
| disabled | si se desactivan todos los componentes del formulario. Si esta en `true` no puede ser cambiado por el prop `disabled` individual de los componentes. | boolean | — | false | | disabled | si se desactivan todos los componentes del formulario. Si esta en `true` no puede ser cambiado por el prop `disabled` individual de los componentes. | boolean | — | false |
### Form Metodos ### Form Metodos
| Metodo | Descripción | Parametros | | Metodo | Descripción | Parametros |
| ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
| validate | el método para validar todo el formulario. Recibe una llamada como parámetro. Después de la validación, la llamada de retorno se ejecutará con dos parámetros: un booleano que indica si la validación ha pasado, y un objeto que contiene todos los campos que fallaron en la validación. Devuelve una promesa si se omite el return | Function(callback: Function(boolean, object)) | | validate | el método para validar todo el formulario. Recibe una llamada como parámetro. Después de la validación, la llamada de retorno se ejecutará con dos parámetros: un booleano que indica si la validación ha pasado, y un objeto que contiene todos los campos que fallaron en la validación. Devuelve una promesa si se omite el return | Function(callback: Function(boolean, object)) |
| validateField | validar uno o varios elementos de formulario | Function(props: string \| array, callback: Function(errorMessage: string)) | | validateField | validar uno o varios elementos de formulario | Function(props: string \| array, callback: Function(errorMessage: string)) |
| resetFields | restablece todos los campos y elimina el resultado de validación | — | | resetFields | restablece todos los campos y elimina el resultado de validación | — |
| clearValidate | borra el mensaje de validación para determinados campos. El parámetro es un prop name o un array de props names de los items del formulario cuyos mensajes de validación se eliminarán. Si se omiten, se borrarán todos los mensajes de validación de los campos. | Function(props: string \| array) | | scrollToField | Scroll to the specified form field | Function(prop: string) |
| clearValidate | borra el mensaje de validación para determinados campos. El parámetro es un prop name o un array de props names de los items del formulario cuyos mensajes de validación se eliminarán. Si se omiten, se borrarán todos los mensajes de validación de los campos. | Function(props: string \| array) |
### Form Events ### Form Events
| Nombre | Descripción | Parametros | | Nombre | Descripción | Parametros |
| -------- | ---------------------------------------------------- | ------------------------------------------------------------ | | -------- | ---------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| validate | se dispara después de validar un ítem del formulario | la propiedad (`prop name`) nombre del ítem del form que se esta validando, si la validación paso o no, y el mensaje de error si existe. | | validate | se dispara después de validar un ítem del formulario | la propiedad (`prop name`) nombre del ítem del form que se esta validando, si la validación paso o no, y el mensaje de error si existe. |
### Form-Item Atributos ### Form-Item Atributos
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto | | Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| -------------- | ------------------------------------------------------------ | ------- | ------------------------------------------- | ----------- | | -------------- | -------------------------------------------------------------------------------------------------------------------- | --------------- | ------------------------------------------ | ----------- |
| prop | un clave del modelo. En el uso del método `validate` y `resetFields`, el atributo es obligatorio. | string | Clave del modelo que se ha pasado a `form` | | | prop | un clave del modelo. En el uso del método `validate` y `resetFields`, el atributo es obligatorio. | string | Clave del modelo que se ha pasado a `form` | |
| label | etiqueta | string | — | — | | label | etiqueta | string | — | — |
| label-width | ancho de la etiqueta, Ejemplo: '50px'. El valor `auto` esta soportado | string / number | — | — | | label-width | ancho de la etiqueta, Ejemplo: '50px'. El valor `auto` esta soportado | string / number | — | — |
| required | si el campo es obligatorio o no, estará determinado por las reglas de validación si se omite. | boolean | — | false | | required | si el campo es obligatorio o no, estará determinado por las reglas de validación si se omite. | boolean | — | false |
| rules | reglas de validación del form, ver más información en [async-validator](https://github.com/yiminghe/async-validator) | object / array | — | — | | rules | reglas de validación del form, ver más información en [async-validator](https://github.com/yiminghe/async-validator) | object / array | — | — |
| error | mensaje de error de campo, establezca su valor y el campo validará el error y mostrará este mensaje inmediatamente. | string | — | — | | error | mensaje de error de campo, establezca su valor y el campo validará el error y mostrará este mensaje inmediatamente. | string | — | — |
| show-message | si mostrar o no el mensaje de error | boolean | — | true | | show-message | si mostrar o no el mensaje de error | boolean | — | true |
| inline-message | mensaje de validación estilo inline | boolean | — | false | | inline-message | mensaje de validación estilo inline | boolean | — | false |
| size | Tamaño de los componentes en este form item | string | medium / small / mini | — | | size | Tamaño de los componentes en este form item | string | medium / small / mini | — |
### Rules ### Rules
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| -------- | ----------------- | ------ | ---- | ---- | | Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| trigger | how the validator is triggered | string | blur / change | — | | -------- | ------------------------------ | ------ | ----------------- | ----------- |
| trigger | how the validator is triggered | string | blur / change | — |
### Form-Item Slot ### Form-Item Slot
| Nombre | Descripción | | Nombre | Descripción |
| ------ | ------------------------ | | ------ | -------------------------------------------------------------------------------------------------- |
| — | contenido del Form Item | | — | contenido del Form Item |
| label | Custom content to display on label. The scope parameter is { label } | | label | Custom content to display on label. The scope parameter is { label } |
| error | Contenido personalizado para mostrar el mensaje de validación. El parámetro del scope es { error } | | error | Contenido personalizado para mostrar el mensaje de validación. El parámetro del scope es { error } |
### Form-Item Metodo ### Form-Item Metodo

View File

@ -25,11 +25,20 @@ Il peut contenir toutes sortes de champs tels que `input`, `select`, `radio` et
</el-form-item> </el-form-item>
<el-form-item label="Activity time"> <el-form-item label="Activity time">
<el-col :span="11"> <el-col :span="11">
<el-date-picker type="date" placeholder="Choisissez une date" v-model="form.date1" style="width: 100%;"></el-date-picker> <el-date-picker
type="date"
placeholder="Choisissez une date"
v-model="form.date1"
style="width: 100%;"
></el-date-picker>
</el-col> </el-col>
<el-col class="line" :span="2">-</el-col> <el-col class="line" :span="2">-</el-col>
<el-col :span="11"> <el-col :span="11">
<el-time-picker placeholder="Pick a time" v-model="form.date2" style="width: 100%;"></el-time-picker> <el-time-picker
placeholder="Pick a time"
v-model="form.date2"
style="width: 100%;"
></el-time-picker>
</el-col> </el-col>
</el-form-item> </el-form-item>
<el-form-item label="Instant delivery"> <el-form-item label="Instant delivery">
@ -69,26 +78,28 @@ Il peut contenir toutes sortes de champs tels que `input`, `select`, `radio` et
delivery: false, delivery: false,
type: [], type: [],
resource: '', resource: '',
desc: '' desc: '',
} },
} }
}, },
methods: { methods: {
onSubmit() { onSubmit() {
console.log('submit!'); console.log('submit!')
} },
} },
} }
</script> </script>
``` ```
::: :::
:::tip :::tip
[W3C](https://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2) stipule que [W3C](https://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2) stipule que
> <i>Lorsqu'il n'y a qu'un seul champ de type texte dans un formulaire, le navigateur devrait accepter la pression de la touche Entrée sur ce champ comme méthode de soumission du formulaire</i> > <i>Lorsqu'il n'y a qu'un seul champ de type texte dans un formulaire, le navigateur devrait accepter la pression de la touche Entrée sur ce champ comme méthode de soumission du formulaire</i>
Pour éviter ce comportement, vous pouvez ajouter `@submit.prevent` dans `<el-form>`. Pour éviter ce comportement, vous pouvez ajouter `@submit.prevent` dans `<el-form>`.
::: :::
### Formulaire horizontal ### Formulaire horizontal
@ -117,18 +128,19 @@ Lorsque l'espace vertical est limité et que le formulaire est relativement simp
return { return {
formInline: { formInline: {
user: '', user: '',
region: '' region: '',
} },
} }
}, },
methods: { methods: {
onSubmit() { onSubmit() {
console.log('submit!'); console.log('submit!')
} },
} },
} }
</script> </script>
``` ```
::: :::
### Alignement ### Alignement
@ -144,7 +156,11 @@ Suivant votre design, il y a différents moyens d'aligner vos labels.
<el-radio-button label="top">Top</el-radio-button> <el-radio-button label="top">Top</el-radio-button>
</el-radio-group> </el-radio-group>
<div style="margin: 20px;"></div> <div style="margin: 20px;"></div>
<el-form :label-position="labelPosition" label-width="100px" :model="formLabelAlign"> <el-form
:label-position="labelPosition"
label-width="100px"
:model="formLabelAlign"
>
<el-form-item label="Name"> <el-form-item label="Name">
<el-input v-model="formLabelAlign.name"></el-input> <el-input v-model="formLabelAlign.name"></el-input>
</el-form-item> </el-form-item>
@ -163,23 +179,30 @@ Suivant votre design, il y a différents moyens d'aligner vos labels.
formLabelAlign: { formLabelAlign: {
name: '', name: '',
region: '', region: '',
type: '' type: '',
} },
}; }
} },
} }
</script> </script>
``` ```
::: :::
### Validation ### Validation
Le composant Form vous permet d'effectuer des vérifications, afin de détecter et corriger les erreurs facilement. Le composant Form vous permet d'effectuer des vérifications, afin de détecter et corriger les erreurs facilement.
:::demo Ajoutez l'attribut `rules` au composant `Form`, passez les règles de validation, et configurez l'attribut `prop` de `Form-Item` pour ajouter la clé de la règle correspondante au champ. Plus d'informations ici: [async-validator](https://github.com/yiminghe/async-validator). :::demo Ajoutez l'attribut `rules` au composant `Form`, passez les règles de validation, et configurez l'attribut `prop` de `Form-Item` pour ajouter la clé de la règle correspondante au champ. Plus d'informations ici: [async-validator](https://github.com/yiminghe/async-validator).
```html ```html
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm"> <el-form
:model="ruleForm"
:rules="rules"
ref="ruleForm"
label-width="120px"
class="demo-ruleForm"
>
<el-form-item label="Activity name" prop="name"> <el-form-item label="Activity name" prop="name">
<el-input v-model="ruleForm.name"></el-input> <el-input v-model="ruleForm.name"></el-input>
</el-form-item> </el-form-item>
@ -192,13 +215,22 @@ Le composant Form vous permet d'effectuer des vérifications, afin de détecter
<el-form-item label="Activity time" required> <el-form-item label="Activity time" required>
<el-col :span="11"> <el-col :span="11">
<el-form-item prop="date1"> <el-form-item prop="date1">
<el-date-picker type="date" placeholder="Choisissez une date" v-model="ruleForm.date1" style="width: 100%;"></el-date-picker> <el-date-picker
type="date"
placeholder="Choisissez une date"
v-model="ruleForm.date1"
style="width: 100%;"
></el-date-picker>
</el-form-item> </el-form-item>
</el-col> </el-col>
<el-col class="line" :span="2">-</el-col> <el-col class="line" :span="2">-</el-col>
<el-col :span="11"> <el-col :span="11">
<el-form-item prop="date2"> <el-form-item prop="date2">
<el-time-picker placeholder="Pick a time" v-model="ruleForm.date2" style="width: 100%;"></el-time-picker> <el-time-picker
placeholder="Pick a time"
v-model="ruleForm.date2"
style="width: 100%;"
></el-time-picker>
</el-form-item> </el-form-item>
</el-col> </el-col>
</el-form-item> </el-form-item>
@ -239,52 +271,89 @@ Le composant Form vous permet d'effectuer des vérifications, afin de détecter
delivery: false, delivery: false,
type: [], type: [],
resource: '', resource: '',
desc: '' desc: '',
}, },
rules: { rules: {
name: [ name: [
{ required: true, message: 'Please input Activity name', trigger: 'blur' }, {
{ min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' } required: true,
message: 'Please input Activity name',
trigger: 'blur',
},
{
min: 3,
max: 5,
message: 'Length should be 3 to 5',
trigger: 'blur',
},
], ],
region: [ region: [
{ required: true, message: 'Please select Activity zone', trigger: 'change' } {
required: true,
message: 'Please select Activity zone',
trigger: 'change',
},
], ],
date1: [ date1: [
{ type: 'date', required: true, message: 'Please pick a date', trigger: 'change' } {
type: 'date',
required: true,
message: 'Please pick a date',
trigger: 'change',
},
], ],
date2: [ date2: [
{ type: 'date', required: true, message: 'Please pick a time', trigger: 'change' } {
type: 'date',
required: true,
message: 'Please pick a time',
trigger: 'change',
},
], ],
type: [ type: [
{ type: 'array', required: true, message: 'Please select at least one activity type', trigger: 'change' } {
type: 'array',
required: true,
message: 'Please select at least one activity type',
trigger: 'change',
},
], ],
resource: [ resource: [
{ required: true, message: 'Please select activity resource', trigger: 'change' } {
required: true,
message: 'Please select activity resource',
trigger: 'change',
},
], ],
desc: [ desc: [
{ required: true, message: 'Please input activity form', trigger: 'blur' } {
] required: true,
} message: 'Please input activity form',
}; trigger: 'blur',
},
],
},
}
}, },
methods: { methods: {
submitForm(formName) { submitForm(formName) {
this.$refs[formName].validate((valid) => { this.$refs[formName].validate(valid => {
if (valid) { if (valid) {
alert('submit!'); alert('submit!')
} else { } else {
console.log('error submit!!'); console.log('error submit!!')
return false; return false
} }
}); })
}, },
resetForm(formName) { resetForm(formName) {
this.$refs[formName].resetFields(); this.$refs[formName].resetFields()
} },
} },
} }
</script> </script>
``` ```
::: :::
### Validations personnalisées ### Validations personnalisées
@ -292,13 +361,29 @@ Le composant Form vous permet d'effectuer des vérifications, afin de détecter
Cet exemple montre comment vous pouvez personnaliser vos règles de validation pour effectuer une identification à deux facteurs. Cet exemple montre comment vous pouvez personnaliser vos règles de validation pour effectuer une identification à deux facteurs.
:::demo Ici, nous utilisons `status-icon` pour afficher le résultat de la validation sous forme d'icône. :::demo Ici, nous utilisons `status-icon` pour afficher le résultat de la validation sous forme d'icône.
```html ```html
<el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm"> <el-form
:model="ruleForm"
status-icon
:rules="rules"
ref="ruleForm"
label-width="120px"
class="demo-ruleForm"
>
<el-form-item label="Password" prop="pass"> <el-form-item label="Password" prop="pass">
<el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input> <el-input
type="password"
v-model="ruleForm.pass"
autocomplete="off"
></el-input>
</el-form-item> </el-form-item>
<el-form-item label="Confirm" prop="checkPass"> <el-form-item label="Confirm" prop="checkPass">
<el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input> <el-input
type="password"
v-model="ruleForm.checkPass"
autocomplete="off"
></el-input>
</el-form-item> </el-form-item>
<el-form-item label="Age" prop="age"> <el-form-item label="Age" prop="age">
<el-input v-model.number="ruleForm.age"></el-input> <el-input v-model.number="ruleForm.age"></el-input>
@ -313,76 +398,71 @@ Cet exemple montre comment vous pouvez personnaliser vos règles de validation p
data() { data() {
var checkAge = (rule, value, callback) => { var checkAge = (rule, value, callback) => {
if (!value) { if (!value) {
return callback(new Error('Veuillez entrer l\'âge')); return callback(new Error("Veuillez entrer l'âge"))
} }
setTimeout(() => { setTimeout(() => {
if (!Number.isInteger(value)) { if (!Number.isInteger(value)) {
callback(new Error('Veuillez entrer des chiffres')); callback(new Error('Veuillez entrer des chiffres'))
} else { } else {
if (value < 18) { if (value < 18) {
callback(new Error('L\'âge doit être supérieur à 18 ans')); callback(new Error("L'âge doit être supérieur à 18 ans"))
} else { } else {
callback(); callback()
} }
} }
}, 1000); }, 1000)
}; }
var validatePass = (rule, value, callback) => { var validatePass = (rule, value, callback) => {
if (value === '') { if (value === '') {
callback(new Error('Veuillez entrer le mot de passe')); callback(new Error('Veuillez entrer le mot de passe'))
} else { } else {
if (this.ruleForm.checkPass !== '') { if (this.ruleForm.checkPass !== '') {
this.$refs.ruleForm.validateField('checkPass'); this.$refs.ruleForm.validateField('checkPass')
} }
callback(); callback()
} }
}; }
var validatePass2 = (rule, value, callback) => { var validatePass2 = (rule, value, callback) => {
if (value === '') { if (value === '') {
callback(new Error('Veuillez entrer à nouveau le mot de passe')); callback(new Error('Veuillez entrer à nouveau le mot de passe'))
} else if (value !== this.ruleForm.pass) { } else if (value !== this.ruleForm.pass) {
callback(new Error('Les deux entrées ne correspondent pas!')); callback(new Error('Les deux entrées ne correspondent pas!'))
} else { } else {
callback(); callback()
} }
}; }
return { return {
ruleForm: { ruleForm: {
pass: '', pass: '',
checkPass: '', checkPass: '',
age: '' age: '',
}, },
rules: { rules: {
pass: [ pass: [{ validator: validatePass, trigger: 'blur' }],
{ validator: validatePass, trigger: 'blur' } checkPass: [{ validator: validatePass2, trigger: 'blur' }],
], age: [{ validator: checkAge, trigger: 'blur' }],
checkPass: [ },
{ validator: validatePass2, trigger: 'blur' } }
],
age: [
{ validator: checkAge, trigger: 'blur' }
]
}
};
}, },
methods: { methods: {
submitForm(formName) { submitForm(formName) {
this.$refs[formName].validate((valid) => { this.$refs[formName].validate(valid => {
if (valid) { if (valid) {
alert('submit!'); alert('submit!')
} else { } else {
console.log('error submit!!'); console.log('error submit!!')
return false; return false
} }
}); })
}, },
resetForm(formName) { resetForm(formName) {
this.$refs[formName].resetFields(); this.$refs[formName].resetFields()
} },
} },
} }
</script> </script>
``` ```
::: :::
:::tip :::tip
@ -392,8 +472,14 @@ Les callback de validations personnalisées doivent être appelées. Un usage pl
### Ajouter ou supprimer des champs dynamiquement ### Ajouter ou supprimer des champs dynamiquement
:::demo En plus de pouvoir passer toutes les règles de validation en une seule fois au formulaire, vous pouvez aussi ajouter ou supprimer des règles sur un seul champ de manière dynamique. :::demo En plus de pouvoir passer toutes les règles de validation en une seule fois au formulaire, vous pouvez aussi ajouter ou supprimer des règles sur un seul champ de manière dynamique.
```html ```html
<el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="120px" class="demo-dynamic"> <el-form
:model="dynamicValidateForm"
ref="dynamicValidateForm"
label-width="120px"
class="demo-dynamic"
>
<el-form-item <el-form-item
prop="email" prop="email"
label="Email" label="Email"
@ -413,12 +499,17 @@ Les callback de validations personnalisées doivent être appelées. Un usage pl
required: true, message: 'domain ne peut pas être null', trigger: 'blur' required: true, message: 'domain ne peut pas être null', trigger: 'blur'
}" }"
> >
<el-input v-model="domain.value"></el-input><el-button @click.prevent="removeDomain(domain)">Supprimer</el-button> <el-input v-model="domain.value"></el-input
><el-button @click.prevent="removeDomain(domain)">Supprimer</el-button>
</el-form-item> </el-form-item>
<el-form-item> <el-form-item>
<el-button type="primary" @click="submitForm('dynamicValidateForm')">Soumettre</el-button> <el-button type="primary" @click="submitForm('dynamicValidateForm')"
>Soumettre</el-button
>
<el-button @click="addDomain">Nouveau domaine</el-button> <el-button @click="addDomain">Nouveau domaine</el-button>
<el-button @click="resetForm('dynamicValidateForm')">Réinitialiser</el-button> <el-button @click="resetForm('dynamicValidateForm')"
>Réinitialiser</el-button
>
</el-form-item> </el-form-item>
</el-form> </el-form>
<script> <script>
@ -426,51 +517,60 @@ Les callback de validations personnalisées doivent être appelées. Un usage pl
data() { data() {
return { return {
dynamicValidateForm: { dynamicValidateForm: {
domains: [{ domains: [
key: 1, {
value: '' key: 1,
}], value: '',
email: '' },
} ],
}; email: '',
},
}
}, },
methods: { methods: {
submitForm(formName) { submitForm(formName) {
this.$refs[formName].validate((valid) => { this.$refs[formName].validate(valid => {
if (valid) { if (valid) {
alert('submit!'); alert('submit!')
} else { } else {
console.log('error submit!!'); console.log('error submit!!')
return false; return false
} }
}); })
}, },
resetForm(formName) { resetForm(formName) {
this.$refs[formName].resetFields(); this.$refs[formName].resetFields()
}, },
removeDomain(item) { removeDomain(item) {
var index = this.dynamicValidateForm.domains.indexOf(item); var index = this.dynamicValidateForm.domains.indexOf(item)
if (index !== -1) { if (index !== -1) {
this.dynamicValidateForm.domains.splice(index, 1); this.dynamicValidateForm.domains.splice(index, 1)
} }
}, },
addDomain() { addDomain() {
this.dynamicValidateForm.domains.push({ this.dynamicValidateForm.domains.push({
key: Date.now(), key: Date.now(),
value: '' value: '',
}); })
} },
} },
} }
</script> </script>
``` ```
::: :::
### Validation des nombres ### Validation des nombres
:::demo Pour valider les nombres correctement, il vous faudra ajouter le modificateur `.number` à l'attribut `v-model`. Il est utilisé par Vuejs pour transformer les valeurs en nombres . :::demo Pour valider les nombres correctement, il vous faudra ajouter le modificateur `.number` à l'attribut `v-model`. Il est utilisé par Vuejs pour transformer les valeurs en nombres .
```html ```html
<el-form :model="numberValidateForm" ref="numberValidateForm" label-width="100px" class="demo-ruleForm"> <el-form
:model="numberValidateForm"
ref="numberValidateForm"
label-width="100px"
class="demo-ruleForm"
>
<el-form-item <el-form-item
label="age" label="age"
prop="age" prop="age"
@ -479,11 +579,19 @@ Les callback de validations personnalisées doivent être appelées. Un usage pl
{ type: 'number', message: 'l\'âge doit être un nombre'} { type: 'number', message: 'l\'âge doit être un nombre'}
]" ]"
> >
<el-input type="age" v-model.number="numberValidateForm.age" autocomplete="off"></el-input> <el-input
type="age"
v-model.number="numberValidateForm.age"
autocomplete="off"
></el-input>
</el-form-item> </el-form-item>
<el-form-item> <el-form-item>
<el-button type="primary" @click="submitForm('numberValidateForm')">Soumettre</el-button> <el-button type="primary" @click="submitForm('numberValidateForm')"
<el-button @click="resetForm('numberValidateForm')">Réinitialiser</el-button> >Soumettre</el-button
>
<el-button @click="resetForm('numberValidateForm')"
>Réinitialiser</el-button
>
</el-form-item> </el-form-item>
</el-form> </el-form>
<script> <script>
@ -491,28 +599,29 @@ Les callback de validations personnalisées doivent être appelées. Un usage pl
data() { data() {
return { return {
numberValidateForm: { numberValidateForm: {
age: '' age: '',
} },
}; }
}, },
methods: { methods: {
submitForm(formName) { submitForm(formName) {
this.$refs[formName].validate((valid) => { this.$refs[formName].validate(valid => {
if (valid) { if (valid) {
alert('submit!'); alert('submit!')
} else { } else {
console.log('error submit!!'); console.log('error submit!!')
return false; return false
} }
}); })
}, },
resetForm(formName) { resetForm(formName) {
this.$refs[formName].resetFields(); this.$refs[formName].resetFields()
} },
} },
} }
</script> </script>
``` ```
::: :::
:::tip :::tip
@ -524,30 +633,49 @@ Lorsqu'un `el-form-item` est imbriqué dans un autre `el-form-item`, la largeur
Tout les composants d'un formulaire héritent leur attribut `size` de ce formulaire. Il est aussi possible de l'utiliser individuellement sur chaque FormItem. Tout les composants d'un formulaire héritent leur attribut `size` de ce formulaire. Il est aussi possible de l'utiliser individuellement sur chaque FormItem.
:::demo Vous pouvez régler le `size` de chaque item si vous ne souhaitez pas qu'il hérite de son parent. :::demo Vous pouvez régler le `size` de chaque item si vous ne souhaitez pas qu'il hérite de son parent.
```html ```html
<el-form ref="form" :model="sizeForm" label-width="120px" size="mini"> <el-form ref="form" :model="sizeForm" label-width="120px" size="mini">
<el-form-item label="Activity name"> <el-form-item label="Activity name">
<el-input v-model="sizeForm.name"></el-input> <el-input v-model="sizeForm.name"></el-input>
</el-form-item> </el-form-item>
<el-form-item label="Activity zone"> <el-form-item label="Activity zone">
<el-select v-model="sizeForm.region" placeholder="veuillez sélectionner votre zone"> <el-select
v-model="sizeForm.region"
placeholder="veuillez sélectionner votre zone"
>
<el-option label="Zone one" value="shanghai"></el-option> <el-option label="Zone one" value="shanghai"></el-option>
<el-option label="Zone two" value="beijing"></el-option> <el-option label="Zone two" value="beijing"></el-option>
</el-select> </el-select>
</el-form-item> </el-form-item>
<el-form-item label="Activity time"> <el-form-item label="Activity time">
<el-col :span="11"> <el-col :span="11">
<el-date-picker type="date" placeholder="Choisissez une date" v-model="sizeForm.date1" style="width: 100%;"></el-date-picker> <el-date-picker
type="date"
placeholder="Choisissez une date"
v-model="sizeForm.date1"
style="width: 100%;"
></el-date-picker>
</el-col> </el-col>
<el-col class="line" :span="2">-</el-col> <el-col class="line" :span="2">-</el-col>
<el-col :span="11"> <el-col :span="11">
<el-time-picker placeholder="Choisissez une heure" v-model="sizeForm.date2" style="width: 100%;"></el-time-picker> <el-time-picker
placeholder="Choisissez une heure"
v-model="sizeForm.date2"
style="width: 100%;"
></el-time-picker>
</el-col> </el-col>
</el-form-item> </el-form-item>
<el-form-item label="Activity type"> <el-form-item label="Activity type">
<el-checkbox-group v-model="sizeForm.type"> <el-checkbox-group v-model="sizeForm.type">
<el-checkbox-button label="Online activities" name="type"></el-checkbox-button> <el-checkbox-button
<el-checkbox-button label="Promotion activities" name="type"></el-checkbox-button> label="Online activities"
name="type"
></el-checkbox-button>
<el-checkbox-button
label="Promotion activities"
name="type"
></el-checkbox-button>
</el-checkbox-group> </el-checkbox-group>
</el-form-item> </el-form-item>
<el-form-item label="Resources"> <el-form-item label="Resources">
@ -574,82 +702,86 @@ Tout les composants d'un formulaire héritent leur attribut `size` de ce formula
delivery: false, delivery: false,
type: [], type: [],
resource: '', resource: '',
desc: '' desc: '',
} },
}; }
}, },
methods: { methods: {
onSubmit() { onSubmit() {
console.log('submit!'); console.log('submit!')
} },
} },
}; }
</script> </script>
``` ```
::: :::
### Attributs de Form ### Attributs de Form
| Attribut | Description | Type | Valeurs acceptées | Défaut | | Attribut | Description | Type | Valeurs acceptées | Défaut |
| ---- | ----| ---- | ---- | ---- | | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | --------------- | --------------------- | ------ |
| model| Données du formulaire. | object | — | — | | model | Données du formulaire. | object | — | — |
| rules | Règles de validation du formulaire. | object | — | — | | rules | Règles de validation du formulaire. | object | — | — |
| inline | Si le formulaire est horizontal. | boolean | — | false | | inline | Si le formulaire est horizontal. | boolean | — | false |
| label-position | Position des labels. Si 'left' ou 'right', `label-width` est aussi requis. | string | left / right / top | right | | label-position | Position des labels. Si 'left' ou 'right', `label-width` est aussi requis. | string | left / right / top | right |
| label-width | Largeur des labels, tout les enfants directs hériteront de cette valeur. La largeur `auto` est supportée. | string / number | — | — | | label-width | Largeur des labels, tout les enfants directs hériteront de cette valeur. La largeur `auto` est supportée. | string / number | — | — |
| label-suffix | Suffixe de labels. | string | — | — | | label-suffix | Suffixe de labels. | string | — | — |
| hide-required-asterisk | Si les champs obligatoires doivent avoir une astérisque rouge (étoile) à coté de leurs labels. | boolean | — | false | | hide-required-asterisk | Si les champs obligatoires doivent avoir une astérisque rouge (étoile) à coté de leurs labels. | boolean | — | false |
| show-message | Si le message d'erreur doit apparaître. | boolean | — | true | | show-message | Si le message d'erreur doit apparaître. | boolean | — | true |
| inline-message | Si le message d'erreur doit apparaître en ligne avec son champ. | boolean | — | false | | inline-message | Si le message d'erreur doit apparaître en ligne avec son champ. | boolean | — | false |
| status-icon | Si une icône indiquant le résultat de validation doit apparaître. | boolean | — | false | | status-icon | Si une icône indiquant le résultat de validation doit apparaître. | boolean | — | false |
| validate-on-rule-change | Si la validation doit se déclencher lorsque `rules` est modifié. | boolean | — | true | | validate-on-rule-change | Si la validation doit se déclencher lorsque `rules` est modifié. | boolean | — | true |
| size | Contrôle la taille des champs du formulaire. | string | medium / small / mini | — | | size | Contrôle la taille des champs du formulaire. | string | medium / small / mini | — |
| disabled | Si tout les champs du formulaire doivent être désactivés. Si `true`, il ne peut pas être modifié par l'attribut `disabled` des enfants. | boolean | — | false | | disabled | Si tout les champs du formulaire doivent être désactivés. Si `true`, il ne peut pas être modifié par l'attribut `disabled` des enfants. | boolean | — | false |
### Méthodes de Form ### Méthodes de Form
| Méthode | Description | Paramètres | | Méthode | Description | Paramètres |
| ---- | ---- | ---- | | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------- |
| validate | Valide le formulaire. Prends une callback en paramètre. Après la validation, la callback est exécutée avec deux paramètres: un boolean indiquant si la validation est bonne, et un objet contenant tout les champs qui ont échoués. Retourne une promesse si aucune callback n'est passée. | Function(callback: Function(boolean, object)) | | validate | Valide le formulaire. Prends une callback en paramètre. Après la validation, la callback est exécutée avec deux paramètres: un boolean indiquant si la validation est bonne, et un objet contenant tout les champs qui ont échoués. Retourne une promesse si aucune callback n'est passée. | Function(callback: Function(boolean, object)) |
| validateField | Valide un ou plusieurs champs du formulaire. | Function(props: string \| array, callback: Function(errorMessage: string)) | | validateField | Valide un ou plusieurs champs du formulaire. | Function(props: string \| array, callback: Function(errorMessage: string)) |
| resetFields | Efface tout les champs et les résultats de validation. | — | | resetFields | Efface tout les champs et les résultats de validation. | — |
| clearValidate | Efface les messages de validation de certains champs. Le paramètre est le nom du champ ou une liste des champs concernés. S'il est omis, tout les champs seront concernés. | Function(props: string \| array) | | scrollToField | Scroll to the specified form field | Function(prop: string) |
| clearValidate | Efface les messages de validation de certains champs. Le paramètre est le nom du champ ou une liste des champs concernés. S'il est omis, tout les champs seront concernés. | Function(props: string \| array) |
### Évènnements de Form ### Évènnements de Form
| Nom | Description | Paramètres | | Nom | Description | Paramètres |
|----------- |------------ |----------- | | -------- | -------------------------------------------- | ---------------------------------------------------------------------------------------- |
| validate | Se déclenche après la validation d'un champ. | Nom du champs qui a été validé, si la validation est bonne et le message d'erreur sinon. | | validate | Se déclenche après la validation d'un champ. | Nom du champs qui a été validé, si la validation est bonne et le message d'erreur sinon. |
### Attributs de FormItem ### Attributs de FormItem
| Attribut | Description | Type | Valeurs acceptées | Défaut | | Attribut | Description | Type | Valeurs acceptées | Défaut |
| ---- | ----| ---- | ---- | ---- | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | --------------- | ----------------------------- | ------ |
| prop | Une des clés de `model`. Utilisés par les méthodes validate et resetFields. Requis. | string | Clés du model passé à `form`. | | prop | Une des clés de `model`. Utilisés par les méthodes validate et resetFields. Requis. | string | Clés du model passé à `form`. |
| label | Le label. | string | — | — | | label | Le label. | string | — | — |
| label-width | Largeur du label, e.g. '50px'. La largeur `auto` est supportée. | string / number | — | — | | label-width | Largeur du label, e.g. '50px'. La largeur `auto` est supportée. | string / number | — | — |
| required | Si le champ est requis ou non. Si omis, sera déterminé par les règles de validation. | boolean | — | false | | required | Si le champ est requis ou non. Si omis, sera déterminé par les règles de validation. | boolean | — | false |
| rules | Règles de validation du formulaire, voir table suivante, plus d'informations ici: [async-validator](https://github.com/yiminghe/async-validator) | object / array | — | — | | rules | Règles de validation du formulaire, voir table suivante, plus d'informations ici: [async-validator](https://github.com/yiminghe/async-validator) | object / array | — | — |
| error | Message d'erreur du champ. S'il est modifié, le champ l'affichera immédiatement. | string | — | — | | error | Message d'erreur du champ. S'il est modifié, le champ l'affichera immédiatement. | string | — | — |
| show-message | Si le message d'erreur doit apparaître. | boolean | — | true | | show-message | Si le message d'erreur doit apparaître. | boolean | — | true |
| inline-message | Si le message d'erreur doit être en ligne avec le champ. | boolean | — | false | | inline-message | Si le message d'erreur doit être en ligne avec le champ. | boolean | — | false |
| size | Contrôle la taille du FormItem. | string | medium / small / mini | — | | size | Contrôle la taille du FormItem. | string | medium / small / mini | — |
### Rules ### Rules
| Attribut | Description | Type | Valeurs acceptées | Défaut |
| -------- | ----------------- | ------ | ---- | ---- | | Attribut | Description | Type | Valeurs acceptées | Défaut |
| trigger | how the validator is triggered | string | blur / change | — | | -------- | ------------------------------ | ------ | ----------------- | ------ |
| trigger | how the validator is triggered | string | blur / change | — |
### Slot de Form-Item ### Slot de Form-Item
| Nom | Description |
|------|--------| | Nom | Description |
| — | Contenu de Form Item. | | ----- | ------------------------------------------------------------------------------------------ |
| label | Custom content to display on label. The scope parameter is { label } | | — | Contenu de Form Item. |
| error | Contenu personnalisé pour les messages de validation. Le paramètre du scope est { error }. | | label | Custom content to display on label. The scope parameter is { label } |
| error | Contenu personnalisé pour les messages de validation. Le paramètre du scope est { error }. |
### Méthodes de Form-Item ### Méthodes de Form-Item
| Méthode | Description | Paramètres | | Méthode | Description | Paramètres |
| ---- | ---- | ---- | | ------------- | ----------------------------------------------- | ---------- |
| resetField | Efface le champ et les résultats de validation. | — | | resetField | Efface le champ et les résultats de validation. | — |
| clearValidate | Efface le status de validation du champ. | — | | clearValidate | Efface le status de validation du champ. | — |

View File

@ -25,11 +25,20 @@ The component has been upgraded with a flex layout to replace the old float layo
</el-form-item> </el-form-item>
<el-form-item label="Activity time"> <el-form-item label="Activity time">
<el-col :span="11"> <el-col :span="11">
<el-date-picker type="date" placeholder="Pick a date" v-model="form.date1" style="width: 100%;"></el-date-picker> <el-date-picker
type="date"
placeholder="Pick a date"
v-model="form.date1"
style="width: 100%;"
></el-date-picker>
</el-col> </el-col>
<el-col class="line" :span="2">-</el-col> <el-col class="line" :span="2">-</el-col>
<el-col :span="11"> <el-col :span="11">
<el-time-picker placeholder="Pick a time" v-model="form.date2" style="width: 100%;"></el-time-picker> <el-time-picker
placeholder="Pick a time"
v-model="form.date2"
style="width: 100%;"
></el-time-picker>
</el-col> </el-col>
</el-form-item> </el-form-item>
<el-form-item label="Instant delivery"> <el-form-item label="Instant delivery">
@ -69,26 +78,28 @@ The component has been upgraded with a flex layout to replace the old float layo
delivery: false, delivery: false,
type: [], type: [],
resource: '', resource: '',
desc: '' desc: '',
} },
} }
}, },
methods: { methods: {
onSubmit() { onSubmit() {
console.log('submit!'); console.log('submit!')
} },
} },
} }
</script> </script>
``` ```
::: :::
:::tip :::tip
[W3C](https://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2) は規制しているのは [W3C](https://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2) は規制しているのは
> <i>フォーム内に1つの単一行テキスト入力フィールドしかない場合、ユーザエージェントは、そのフィールドでのEnterをフォームの送信要求として受け入れるべきである。</i>
> <i>フォーム内に 1 つの単一行テキスト入力フィールドしかない場合、ユーザエージェントは、そのフィールドでの Enter をフォームの送信要求として受け入れるべきである。</i>
この動作を防ぐには、`<el-form>` に `@submit.prevent` を追加します。 この動作を防ぐには、`<el-form>` に `@submit.prevent` を追加します。
::: :::
### インラインフォーム ### インラインフォーム
@ -117,18 +128,19 @@ The component has been upgraded with a flex layout to replace the old float layo
return { return {
formInline: { formInline: {
user: '', user: '',
region: '' region: '',
} },
} }
}, },
methods: { methods: {
onSubmit() { onSubmit() {
console.log('submit!'); console.log('submit!')
} },
} },
} }
</script> </script>
``` ```
::: :::
### アライメント ### アライメント
@ -144,7 +156,11 @@ The component has been upgraded with a flex layout to replace the old float layo
<el-radio-button label="top">Top</el-radio-button> <el-radio-button label="top">Top</el-radio-button>
</el-radio-group> </el-radio-group>
<div style="margin: 20px;"></div> <div style="margin: 20px;"></div>
<el-form :label-position="labelPosition" label-width="100px" :model="formLabelAlign"> <el-form
:label-position="labelPosition"
label-width="100px"
:model="formLabelAlign"
>
<el-form-item label="Name"> <el-form-item label="Name">
<el-input v-model="formLabelAlign.name"></el-input> <el-input v-model="formLabelAlign.name"></el-input>
</el-form-item> </el-form-item>
@ -163,13 +179,14 @@ The component has been upgraded with a flex layout to replace the old float layo
formLabelAlign: { formLabelAlign: {
name: '', name: '',
region: '', region: '',
type: '' type: '',
} },
}; }
} },
} }
</script> </script>
``` ```
::: :::
### バリデーション ### バリデーション
@ -179,7 +196,13 @@ The component has been upgraded with a flex layout to replace the old float layo
:::demo `Form` コンポーネントに `rules` 属性を追加して検証ルールを渡し、`Form-Item`に `prop` 属性を検証が必要な特定のキーとして設定するだけです。詳細は [async-validator](https://github.com/yiminghe/async-validator) を参照してください。 :::demo `Form` コンポーネントに `rules` 属性を追加して検証ルールを渡し、`Form-Item`に `prop` 属性を検証が必要な特定のキーとして設定するだけです。詳細は [async-validator](https://github.com/yiminghe/async-validator) を参照してください。
```html ```html
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm"> <el-form
:model="ruleForm"
:rules="rules"
ref="ruleForm"
label-width="120px"
class="demo-ruleForm"
>
<el-form-item label="Activity name" prop="name"> <el-form-item label="Activity name" prop="name">
<el-input v-model="ruleForm.name"></el-input> <el-input v-model="ruleForm.name"></el-input>
</el-form-item> </el-form-item>
@ -192,13 +215,22 @@ The component has been upgraded with a flex layout to replace the old float layo
<el-form-item label="Activity time" required> <el-form-item label="Activity time" required>
<el-col :span="11"> <el-col :span="11">
<el-form-item prop="date1"> <el-form-item prop="date1">
<el-date-picker type="date" placeholder="Pick a date" v-model="ruleForm.date1" style="width: 100%;"></el-date-picker> <el-date-picker
type="date"
placeholder="Pick a date"
v-model="ruleForm.date1"
style="width: 100%;"
></el-date-picker>
</el-form-item> </el-form-item>
</el-col> </el-col>
<el-col class="line" :span="2">-</el-col> <el-col class="line" :span="2">-</el-col>
<el-col :span="11"> <el-col :span="11">
<el-form-item prop="date2"> <el-form-item prop="date2">
<el-time-picker placeholder="Pick a time" v-model="ruleForm.date2" style="width: 100%;"></el-time-picker> <el-time-picker
placeholder="Pick a time"
v-model="ruleForm.date2"
style="width: 100%;"
></el-time-picker>
</el-form-item> </el-form-item>
</el-col> </el-col>
</el-form-item> </el-form-item>
@ -239,67 +271,119 @@ The component has been upgraded with a flex layout to replace the old float layo
delivery: false, delivery: false,
type: [], type: [],
resource: '', resource: '',
desc: '' desc: '',
}, },
rules: { rules: {
name: [ name: [
{ required: true, message: 'Please input Activity name', trigger: 'blur' }, {
{ min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' } required: true,
message: 'Please input Activity name',
trigger: 'blur',
},
{
min: 3,
max: 5,
message: 'Length should be 3 to 5',
trigger: 'blur',
},
], ],
region: [ region: [
{ required: true, message: 'Please select Activity zone', trigger: 'change' } {
required: true,
message: 'Please select Activity zone',
trigger: 'change',
},
], ],
date1: [ date1: [
{ type: 'date', required: true, message: 'Please pick a date', trigger: 'change' } {
type: 'date',
required: true,
message: 'Please pick a date',
trigger: 'change',
},
], ],
date2: [ date2: [
{ type: 'date', required: true, message: 'Please pick a time', trigger: 'change' } {
type: 'date',
required: true,
message: 'Please pick a time',
trigger: 'change',
},
], ],
type: [ type: [
{ type: 'array', required: true, message: 'Please select at least one activity type', trigger: 'change' } {
type: 'array',
required: true,
message: 'Please select at least one activity type',
trigger: 'change',
},
], ],
resource: [ resource: [
{ required: true, message: 'Please select activity resource', trigger: 'change' } {
required: true,
message: 'Please select activity resource',
trigger: 'change',
},
], ],
desc: [ desc: [
{ required: true, message: 'Please input activity form', trigger: 'blur' } {
] required: true,
} message: 'Please input activity form',
}; trigger: 'blur',
},
],
},
}
}, },
methods: { methods: {
submitForm(formName) { submitForm(formName) {
this.$refs[formName].validate((valid) => { this.$refs[formName].validate(valid => {
if (valid) { if (valid) {
alert('submit!'); alert('submit!')
} else { } else {
console.log('error submit!!'); console.log('error submit!!')
return false; return false
} }
}); })
}, },
resetForm(formName) { resetForm(formName) {
this.$refs[formName].resetFields(); this.$refs[formName].resetFields()
} },
} },
} }
</script> </script>
``` ```
::: :::
### カスタムバリデーションルール ### カスタムバリデーションルール
この例では、独自の検証ルールをカスタマイズして、2 ファクタのパスワード検証を完了させる方法を示しています。
この例では、独自の検証ルールをカスタマイズして、2ファクタのパスワード検証を完了させる方法を示しています。
:::demo ここでは、検証結果をアイコンとして反映させるために `status-icon` を用いる。 :::demo ここでは、検証結果をアイコンとして反映させるために `status-icon` を用いる。
```html ```html
<el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm"> <el-form
:model="ruleForm"
status-icon
:rules="rules"
ref="ruleForm"
label-width="120px"
class="demo-ruleForm"
>
<el-form-item label="Password" prop="pass"> <el-form-item label="Password" prop="pass">
<el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input> <el-input
type="password"
v-model="ruleForm.pass"
autocomplete="off"
></el-input>
</el-form-item> </el-form-item>
<el-form-item label="Confirm" prop="checkPass"> <el-form-item label="Confirm" prop="checkPass">
<el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input> <el-input
type="password"
v-model="ruleForm.checkPass"
autocomplete="off"
></el-input>
</el-form-item> </el-form-item>
<el-form-item label="Age" prop="age"> <el-form-item label="Age" prop="age">
<el-input v-model.number="ruleForm.age"></el-input> <el-input v-model.number="ruleForm.age"></el-input>
@ -314,76 +398,71 @@ The component has been upgraded with a flex layout to replace the old float layo
data() { data() {
var checkAge = (rule, value, callback) => { var checkAge = (rule, value, callback) => {
if (!value) { if (!value) {
return callback(new Error('Please input the age')); return callback(new Error('Please input the age'))
} }
setTimeout(() => { setTimeout(() => {
if (!Number.isInteger(value)) { if (!Number.isInteger(value)) {
callback(new Error('Please input digits')); callback(new Error('Please input digits'))
} else { } else {
if (value < 18) { if (value < 18) {
callback(new Error('Age must be greater than 18')); callback(new Error('Age must be greater than 18'))
} else { } else {
callback(); callback()
} }
} }
}, 1000); }, 1000)
}; }
var validatePass = (rule, value, callback) => { var validatePass = (rule, value, callback) => {
if (value === '') { if (value === '') {
callback(new Error('Please input the password')); callback(new Error('Please input the password'))
} else { } else {
if (this.ruleForm.checkPass !== '') { if (this.ruleForm.checkPass !== '') {
this.$refs.ruleForm.validateField('checkPass'); this.$refs.ruleForm.validateField('checkPass')
} }
callback(); callback()
} }
}; }
var validatePass2 = (rule, value, callback) => { var validatePass2 = (rule, value, callback) => {
if (value === '') { if (value === '') {
callback(new Error('Please input the password again')); callback(new Error('Please input the password again'))
} else if (value !== this.ruleForm.pass) { } else if (value !== this.ruleForm.pass) {
callback(new Error('Two inputs don\'t match!')); callback(new Error("Two inputs don't match!"))
} else { } else {
callback(); callback()
} }
}; }
return { return {
ruleForm: { ruleForm: {
pass: '', pass: '',
checkPass: '', checkPass: '',
age: '' age: '',
}, },
rules: { rules: {
pass: [ pass: [{ validator: validatePass, trigger: 'blur' }],
{ validator: validatePass, trigger: 'blur' } checkPass: [{ validator: validatePass2, trigger: 'blur' }],
], age: [{ validator: checkAge, trigger: 'blur' }],
checkPass: [ },
{ validator: validatePass2, trigger: 'blur' } }
],
age: [
{ validator: checkAge, trigger: 'blur' }
]
}
};
}, },
methods: { methods: {
submitForm(formName) { submitForm(formName) {
this.$refs[formName].validate((valid) => { this.$refs[formName].validate(valid => {
if (valid) { if (valid) {
alert('submit!'); alert('submit!')
} else { } else {
console.log('error submit!!'); console.log('error submit!!')
return false; return false
} }
}); })
}, },
resetForm(formName) { resetForm(formName) {
this.$refs[formName].resetFields(); this.$refs[formName].resetFields()
} },
} },
} }
</script> </script>
``` ```
::: :::
:::tip :::tip
@ -395,7 +474,12 @@ The component has been upgraded with a flex layout to replace the old float layo
:::demo フォームコンポーネントにすべてのバリデーションルールを一度に渡すことに加えて、単一のフォームフィールドにバリデーションルールを動的に渡したり削除したりすることもできます。 :::demo フォームコンポーネントにすべてのバリデーションルールを一度に渡すことに加えて、単一のフォームフィールドにバリデーションルールを動的に渡したり削除したりすることもできます。
```html ```html
<el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="120px" class="demo-dynamic"> <el-form
:model="dynamicValidateForm"
ref="dynamicValidateForm"
label-width="120px"
class="demo-dynamic"
>
<el-form-item <el-form-item
prop="email" prop="email"
label="Email" label="Email"
@ -415,10 +499,13 @@ The component has been upgraded with a flex layout to replace the old float layo
required: true, message: 'domain can not be null', trigger: 'blur' required: true, message: 'domain can not be null', trigger: 'blur'
}" }"
> >
<el-input v-model="domain.value"></el-input><el-button @click.prevent="removeDomain(domain)">Delete</el-button> <el-input v-model="domain.value"></el-input
><el-button @click.prevent="removeDomain(domain)">Delete</el-button>
</el-form-item> </el-form-item>
<el-form-item> <el-form-item>
<el-button type="primary" @click="submitForm('dynamicValidateForm')">Submit</el-button> <el-button type="primary" @click="submitForm('dynamicValidateForm')"
>Submit</el-button
>
<el-button @click="addDomain">New domain</el-button> <el-button @click="addDomain">New domain</el-button>
<el-button @click="resetForm('dynamicValidateForm')">Reset</el-button> <el-button @click="resetForm('dynamicValidateForm')">Reset</el-button>
</el-form-item> </el-form-item>
@ -428,51 +515,60 @@ The component has been upgraded with a flex layout to replace the old float layo
data() { data() {
return { return {
dynamicValidateForm: { dynamicValidateForm: {
domains: [{ domains: [
key: 1, {
value: '' key: 1,
}], value: '',
email: '' },
} ],
}; email: '',
},
}
}, },
methods: { methods: {
submitForm(formName) { submitForm(formName) {
this.$refs[formName].validate((valid) => { this.$refs[formName].validate(valid => {
if (valid) { if (valid) {
alert('submit!'); alert('submit!')
} else { } else {
console.log('error submit!!'); console.log('error submit!!')
return false; return false
} }
}); })
}, },
resetForm(formName) { resetForm(formName) {
this.$refs[formName].resetFields(); this.$refs[formName].resetFields()
}, },
removeDomain(item) { removeDomain(item) {
var index = this.dynamicValidateForm.domains.indexOf(item); var index = this.dynamicValidateForm.domains.indexOf(item)
if (index !== -1) { if (index !== -1) {
this.dynamicValidateForm.domains.splice(index, 1); this.dynamicValidateForm.domains.splice(index, 1)
} }
}, },
addDomain() { addDomain() {
this.dynamicValidateForm.domains.push({ this.dynamicValidateForm.domains.push({
key: Date.now(), key: Date.now(),
value: '' value: '',
}); })
} },
} },
} }
</script> </script>
``` ```
::: :::
### ナンバーの検証(Number Validate) ### ナンバーの検証(Number Validate)
:::demo Number Validateでは、入力された `v-model` バインディングに `.number` という修飾子を追加する必要がありますが、これは文字列の値をVuejsが提供する数値に変換するために使われます。 :::demo Number Validate では、入力された `v-model` バインディングに `.number` という修飾子を追加する必要がありますが、これは文字列の値を Vuejs が提供する数値に変換するために使われます。
```html ```html
<el-form :model="numberValidateForm" ref="numberValidateForm" label-width="100px" class="demo-ruleForm"> <el-form
:model="numberValidateForm"
ref="numberValidateForm"
label-width="100px"
class="demo-ruleForm"
>
<el-form-item <el-form-item
label="age" label="age"
prop="age" prop="age"
@ -481,10 +577,16 @@ The component has been upgraded with a flex layout to replace the old float layo
{ type: 'number', message: 'age must be a number'} { type: 'number', message: 'age must be a number'}
]" ]"
> >
<el-input type="age" v-model.number="numberValidateForm.age" autocomplete="off"></el-input> <el-input
type="age"
v-model.number="numberValidateForm.age"
autocomplete="off"
></el-input>
</el-form-item> </el-form-item>
<el-form-item> <el-form-item>
<el-button type="primary" @click="submitForm('numberValidateForm')">Submit</el-button> <el-button type="primary" @click="submitForm('numberValidateForm')"
>Submit</el-button
>
<el-button @click="resetForm('numberValidateForm')">Reset</el-button> <el-button @click="resetForm('numberValidateForm')">Reset</el-button>
</el-form-item> </el-form-item>
</el-form> </el-form>
@ -493,28 +595,29 @@ The component has been upgraded with a flex layout to replace the old float layo
data() { data() {
return { return {
numberValidateForm: { numberValidateForm: {
age: '' age: '',
} },
}; }
}, },
methods: { methods: {
submitForm(formName) { submitForm(formName) {
this.$refs[formName].validate((valid) => { this.$refs[formName].validate(valid => {
if (valid) { if (valid) {
alert('submit!'); alert('submit!')
} else { } else {
console.log('error submit!!'); console.log('error submit!!')
return false; return false
} }
}); })
}, },
resetForm(formName) { resetForm(formName) {
this.$refs[formName].resetFields(); this.$refs[formName].resetFields()
} },
} },
} }
</script> </script>
``` ```
::: :::
:::tip :::tip
@ -526,6 +629,7 @@ The component has been upgraded with a flex layout to replace the old float layo
フォームのすべてのコンポーネントはそのフォームから `size` 属性を継承します。同様に、FormItem にも `size` 属性があります。 フォームのすべてのコンポーネントはそのフォームから `size` 属性を継承します。同様に、FormItem にも `size` 属性があります。
:::demo それでも、コンポーネントのサイズを From や FormIten から継承させたくない場合は、各コンポーネントの `size` を微調整することができます。 :::demo それでも、コンポーネントのサイズを From や FormIten から継承させたくない場合は、各コンポーネントの `size` を微調整することができます。
```html ```html
<el-form ref="form" :model="sizeForm" label-width="120px" size="mini"> <el-form ref="form" :model="sizeForm" label-width="120px" size="mini">
<el-form-item label="Activity name"> <el-form-item label="Activity name">
@ -539,17 +643,32 @@ The component has been upgraded with a flex layout to replace the old float layo
</el-form-item> </el-form-item>
<el-form-item label="Activity time"> <el-form-item label="Activity time">
<el-col :span="11"> <el-col :span="11">
<el-date-picker type="date" placeholder="Pick a date" v-model="sizeForm.date1" style="width: 100%;"></el-date-picker> <el-date-picker
type="date"
placeholder="Pick a date"
v-model="sizeForm.date1"
style="width: 100%;"
></el-date-picker>
</el-col> </el-col>
<el-col class="line" :span="2">-</el-col> <el-col class="line" :span="2">-</el-col>
<el-col :span="11"> <el-col :span="11">
<el-time-picker placeholder="Pick a time" v-model="sizeForm.date2" style="width: 100%;"></el-time-picker> <el-time-picker
placeholder="Pick a time"
v-model="sizeForm.date2"
style="width: 100%;"
></el-time-picker>
</el-col> </el-col>
</el-form-item> </el-form-item>
<el-form-item label="Activity type"> <el-form-item label="Activity type">
<el-checkbox-group v-model="sizeForm.type"> <el-checkbox-group v-model="sizeForm.type">
<el-checkbox-button label="Online activities" name="type"></el-checkbox-button> <el-checkbox-button
<el-checkbox-button label="Promotion activities" name="type"></el-checkbox-button> label="Online activities"
name="type"
></el-checkbox-button>
<el-checkbox-button
label="Promotion activities"
name="type"
></el-checkbox-button>
</el-checkbox-group> </el-checkbox-group>
</el-form-item> </el-form-item>
<el-form-item label="Resources"> <el-form-item label="Resources">
@ -576,81 +695,86 @@ The component has been upgraded with a flex layout to replace the old float layo
delivery: false, delivery: false,
type: [], type: [],
resource: '', resource: '',
desc: '' desc: '',
} },
}; }
}, },
methods: { methods: {
onSubmit() { onSubmit() {
console.log('submit!'); console.log('submit!')
} },
} },
}; }
</script> </script>
``` ```
::: :::
### フォーム属性 ### フォーム属性
| Attribute | Description | Type | Accepted Values | Default | | Attribute | Description | Type | Accepted Values | Default |
| ---- | ----| ---- | ---- | ---- | | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | --------------------- | ------- |
| model| フォームコンポーネントのデータ | object | — | — | | model | フォームコンポーネントのデータ | object | — | — |
| rules | フォームのバリデーションルール | object | — | — | | rules | フォームのバリデーションルール | object | — | — |
| inline | フォームがインラインであるかどうか | boolean | — | false | | inline | フォームがインラインであるかどうか | boolean | — | false |
| label-position | ラベルの位置。left'、right もしくは`label-width`が設定されている場合は propも必要です。 | string | left / right / top | right | | label-position | ラベルの位置。left'、right もしくは`label-width`が設定されている場合は prop も必要です。 | string | left / right / top | right |
| label-width | ラベルの幅、例えば '50px'。直接の子フォーム項目はすべてこの値を継承します。Width `auto` がサポートされています。 | string / number | — | — | | label-width | ラベルの幅、例えば '50px'。直接の子フォーム項目はすべてこの値を継承します。Width `auto` がサポートされています。 | string / number | — | — |
| label-suffix | ラベルの接尾辞 | string | — | — | | label-suffix | ラベルの接尾辞 | string | — | — |
| hide-required-asterisk | 必須フィールドのラベルの横に赤いアスタリスク(星)を付けるかどうか | boolean | — | false | | hide-required-asterisk | 必須フィールドのラベルの横に赤いアスタリスク(星)を付けるかどうか | boolean | — | false |
| show-message | エラーメッセージを表示するかどうか | boolean | — | true | | show-message | エラーメッセージを表示するかどうか | boolean | — | true |
| inline-message | エラーメッセージをフォーム項目とインラインで表示するかどうか。 | boolean | — | false | | inline-message | エラーメッセージをフォーム項目とインラインで表示するかどうか。 | boolean | — | false |
| status-icon | バリデーション結果を示すアイコンを表示するかどうか | boolean | — | false | | status-icon | バリデーション結果を示すアイコンを表示するかどうか | boolean | — | false |
| validate-on-rule-change | `rules` propが変更されたときにバリデーションをトリガするかどうか。 | boolean | — | true | | validate-on-rule-change | `rules` prop が変更されたときにバリデーションをトリガするかどうか。 | boolean | — | true |
| size | コンポーネントのサイズを制御する形式 | string | medium / small / mini | — | | size | コンポーネントのサイズを制御する形式 | string | medium / small / mini | — |
| disabled | このフォームのすべてのコンポーネントを無効にするかどうかを指定します。true に設定されている場合、内部のコンポーネントの `disabled` プロップで上書きすることはできません。 | boolean | — | false | | disabled | このフォームのすべてのコンポーネントを無効にするかどうかを指定します。true に設定されている場合、内部のコンポーネントの `disabled` プロップで上書きすることはできません。 | boolean | — | false |
### フォームメソッド ### フォームメソッド
| Method | Description | Parameters | | Method | Description | Parameters |
| ---- | ---- | ---- | | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
| validate | バリデートはフォーム全体を検証します。パラメータとしてコールバックを受け取ります。バリデーションが通過したかどうかを示すブール値と、バリデーションに失敗したすべてのフィールドを含むオブジェクトです。コールバックが省略された場合はpromiseを返します。 | Function(callback: Function(boolean, object)) | | validate | バリデートはフォーム全体を検証します。パラメータとしてコールバックを受け取ります。バリデーションが通過したかどうかを示すブール値と、バリデーションに失敗したすべてのフィールドを含むオブジェクトです。コールバックが省略された場合は promise を返します。 | Function(callback: Function(boolean, object)) |
| validateField | フォーム項目を検証する | Function(props: string \| array, callback: Function(errorMessage: string)) | | validateField | フォーム項目を検証する | Function(props: string \| array, callback: Function(errorMessage: string)) |
| resetFields | すべてのフィールドをリセットし、検証結果を削除します。 | — | | resetFields | すべてのフィールドをリセットし、検証結果を削除します。 | — |
| clearValidate | 特定のフィールドのバリデーションメッセージをクリアします。パラメータはprop名、または検証メッセージが削除されるフォーム項目のprop名の配列です。省略された場合、すべてのフィールドのバリデーションメッセージがクリアされます。 | Function(props: string \| array) | | scrollToField | 指定されたフォームフィールドまでスクロールします | Function(prop: string) |
| clearValidate | 特定のフィールドのバリデーションメッセージをクリアします。パラメータは prop 名、または検証メッセージが削除されるフォーム項目の prop 名の配列です。省略された場合、すべてのフィールドのバリデーションメッセージがクリアされます。 | Function(props: string \| array) |
### フォームイベント ### フォームイベント
| Event Name | Description | Parameters |
|----------- |------------ |----------- | | Event Name | Description | Parameters |
| ---------- | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| validate | フォーム項目バリデーション後にトリガされます。 | prop name of the form item being validated, whether validation is passed and the error message if not | | validate | フォーム項目バリデーション後にトリガされます。 | prop name of the form item being validated, whether validation is passed and the error message if not |
### フォームアイテム属性 ### フォームアイテム属性
| Attribute | Description | Type | Accepted Values | Default | | Attribute | Description | Type | Accepted Values | Default |
| ---- | ----| ---- | ---- | ---- | | -------------- | ------------------------------------------------------------------------------------------------------------ | --------------- | ----------------------------------- | ------- |
| prop | `model` のキーです。validateメソッドとresetFieldsメソッドを利用する際には、この属性が必須です。 | string | keys of model that passed to `form` | | prop | `model` のキーです。validate メソッドと resetFields メソッドを利用する際には、この属性が必須です。 | string | keys of model that passed to `form` |
| label | ラベル | string | — | — | | label | ラベル | string | — | — |
| label-width | ラベルの幅。Width `auto` がサポートされています。 | string / number | — | — | | label-width | ラベルの幅。Width `auto` がサポートされています。 | string / number | — | — |
| required | フィールドが必須かどうか、省略された場合はバリデーションルールによって決定されます。 | boolean | — | false | | required | フィールドが必須かどうか、省略された場合はバリデーションルールによって決定されます。 | boolean | — | false |
| rules | フォームのバリデーションルール | object / array | — | — | | rules | フォームのバリデーションルール | object / array | — | — |
| error | フィールドのエラーメッセージ、値を設定すると、フィールドはエラーを検証し、このメッセージをすぐに表示します。 | string | — | — | | error | フィールドのエラーメッセージ、値を設定すると、フィールドはエラーを検証し、このメッセージをすぐに表示します。 | string | — | — |
| show-message | エラーメッセージを表示するかどうか | boolean | — | true | | show-message | エラーメッセージを表示するかどうか | boolean | — | true |
| inline-message | インラインスタイルバリデートメッセージ | boolean | — | false | | inline-message | インラインスタイルバリデートメッセージ | boolean | — | false |
| size | フォームアイテムのコンポーネントのサイズを制御します。 | string | medium / small / mini | — | | size | フォームアイテムのコンポーネントのサイズを制御します。 | string | medium / small / mini | — |
### Rules ### Rules
| Attribute | Description | Type | Accepted Values | Default |
| -------- | ----------------- | ------ | ---- | ---- | | Attribute | Description | Type | Accepted Values | Default |
| trigger | how the validator is triggered | string | blur / change | — | | --------- | ------------------------------ | ------ | --------------- | ------- |
| trigger | how the validator is triggered | string | blur / change | — |
### フォームアイテムスロット ### フォームアイテムスロット
| Name | Description |
|------|--------| | Name | Description |
| — | フォームアイテムの内容 | | ----- | ------------------------------------------------------------------------------ |
| label | Custom content to display on label. The scope parameter is { label } | | — | フォームアイテムの内容 |
| error | Custom content to display validation message. The scope parameter is { error } | | label | Custom content to display on label. The scope parameter is { label } |
| error | Custom content to display validation message. The scope parameter is { error } |
### フォームアイテムのメソッド ### フォームアイテムのメソッド
| Method | Description | Parameters | | Method | Description | Parameters |
| ---- | ---- | ---- | | ------------- | ---------------------------------------------------------- | ---------- |
| resetField | 現在のフィールドをリセットしてバリデーション結果を削除する | — | | resetField | 現在のフィールドをリセットしてバリデーション結果を削除する | — |
| clearValidate | フィールドのバリデーションステータスを削除する | — | | clearValidate | フィールドのバリデーションステータスを削除する | — |

View File

@ -11,6 +11,7 @@
包括各种表单项,比如输入框、选择器、开关、单选框、多选框等。 包括各种表单项,比如输入框、选择器、开关、单选框、多选框等。
:::demo 在 Form 组件中,每一个表单域由一个 Form-Item 组件构成,表单域中可以放置各种类型的表单控件,包括 Input、Select、Checkbox、Radio、Switch、DatePicker、TimePicker :::demo 在 Form 组件中,每一个表单域由一个 Form-Item 组件构成,表单域中可以放置各种类型的表单控件,包括 Input、Select、Checkbox、Radio、Switch、DatePicker、TimePicker
```html ```html
<el-form ref="form" :model="form" label-width="80px"> <el-form ref="form" :model="form" label-width="80px">
<el-form-item label="活动名称"> <el-form-item label="活动名称">
@ -24,11 +25,20 @@
</el-form-item> </el-form-item>
<el-form-item label="活动时间"> <el-form-item label="活动时间">
<el-col :span="11"> <el-col :span="11">
<el-date-picker type="date" placeholder="选择日期" v-model="form.date1" style="width: 100%;"></el-date-picker> <el-date-picker
type="date"
placeholder="选择日期"
v-model="form.date1"
style="width: 100%;"
></el-date-picker>
</el-col> </el-col>
<el-col class="line" :span="2">-</el-col> <el-col class="line" :span="2">-</el-col>
<el-col :span="11"> <el-col :span="11">
<el-time-picker placeholder="选择时间" v-model="form.date2" style="width: 100%;"></el-time-picker> <el-time-picker
placeholder="选择时间"
v-model="form.date2"
style="width: 100%;"
></el-time-picker>
</el-col> </el-col>
</el-form-item> </el-form-item>
<el-form-item label="即时配送"> <el-form-item label="即时配送">
@ -68,22 +78,24 @@
delivery: false, delivery: false,
type: [], type: [],
resource: '', resource: '',
desc: '' desc: '',
} },
} }
}, },
methods: { methods: {
onSubmit() { onSubmit() {
console.log('submit!'); console.log('submit!')
} },
} },
} }
</script> </script>
``` ```
::: :::
:::tip :::tip
W3C 标准中有如下[规定](https://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2) W3C 标准中有如下[规定](https://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2)
> <i>When there is only one single-line text input field in a form, the user agent should accept Enter in that field as a request to submit the form.</i> > <i>When there is only one single-line text input field in a form, the user agent should accept Enter in that field as a request to submit the form.</i>
即:当一个 form 元素中只有一个输入框时,在该输入框中按下回车应提交该表单。如果希望阻止这一默认行为,可以在 `<el-form>` 标签上添加 `@submit.prevent` 即:当一个 form 元素中只有一个输入框时,在该输入框中按下回车应提交该表单。如果希望阻止这一默认行为,可以在 `<el-form>` 标签上添加 `@submit.prevent`
@ -94,6 +106,7 @@ W3C 标准中有如下[规定](https://www.w3.org/MarkUp/html-spec/html-spec_8.h
当垂直方向空间受限且表单较简单时,可以在一行内放置表单。 当垂直方向空间受限且表单较简单时,可以在一行内放置表单。
:::demo 设置 `inline` 属性可以让表单域变为行内的表单域 :::demo 设置 `inline` 属性可以让表单域变为行内的表单域
```html ```html
<el-form :inline="true" :model="formInline" class="demo-form-inline"> <el-form :inline="true" :model="formInline" class="demo-form-inline">
<el-form-item label="审批人"> <el-form-item label="审批人">
@ -115,18 +128,19 @@ W3C 标准中有如下[规定](https://www.w3.org/MarkUp/html-spec/html-spec_8.h
return { return {
formInline: { formInline: {
user: '', user: '',
region: '' region: '',
} },
} }
}, },
methods: { methods: {
onSubmit() { onSubmit() {
console.log('submit!'); console.log('submit!')
} },
} },
} }
</script> </script>
``` ```
::: :::
### 对齐方式 ### 对齐方式
@ -134,6 +148,7 @@ W3C 标准中有如下[规定](https://www.w3.org/MarkUp/html-spec/html-spec_8.h
根据具体目标和制约因素,选择最佳的标签对齐方式。 根据具体目标和制约因素,选择最佳的标签对齐方式。
:::demo 通过设置 `label-position` 属性可以改变表单域标签的位置,可选值为 `top`、`left`,当设为 `top` 时标签会置于表单域的顶部 :::demo 通过设置 `label-position` 属性可以改变表单域标签的位置,可选值为 `top`、`left`,当设为 `top` 时标签会置于表单域的顶部
```html ```html
<el-radio-group v-model="labelPosition" size="small"> <el-radio-group v-model="labelPosition" size="small">
<el-radio-button label="left">左对齐</el-radio-button> <el-radio-button label="left">左对齐</el-radio-button>
@ -141,7 +156,11 @@ W3C 标准中有如下[规定](https://www.w3.org/MarkUp/html-spec/html-spec_8.h
<el-radio-button label="top">顶部对齐</el-radio-button> <el-radio-button label="top">顶部对齐</el-radio-button>
</el-radio-group> </el-radio-group>
<div style="margin: 20px;"></div> <div style="margin: 20px;"></div>
<el-form :label-position="labelPosition" label-width="80px" :model="formLabelAlign"> <el-form
:label-position="labelPosition"
label-width="80px"
:model="formLabelAlign"
>
<el-form-item label="名称"> <el-form-item label="名称">
<el-input v-model="formLabelAlign.name"></el-input> <el-input v-model="formLabelAlign.name"></el-input>
</el-form-item> </el-form-item>
@ -160,13 +179,14 @@ W3C 标准中有如下[规定](https://www.w3.org/MarkUp/html-spec/html-spec_8.h
formLabelAlign: { formLabelAlign: {
name: '', name: '',
region: '', region: '',
type: '' type: '',
} },
}; }
} },
} }
</script> </script>
``` ```
::: :::
### 表单验证 ### 表单验证
@ -174,8 +194,15 @@ W3C 标准中有如下[规定](https://www.w3.org/MarkUp/html-spec/html-spec_8.h
在防止用户犯错的前提下,尽可能让用户更早地发现并纠正错误。 在防止用户犯错的前提下,尽可能让用户更早地发现并纠正错误。
:::demo Form 组件提供了表单验证的功能,只需要通过 `rules` 属性传入约定的验证规则,并将 Form-Item 的 `prop` 属性设置为需校验的字段名即可。校验规则参见 [async-validator](https://github.com/yiminghe/async-validator) :::demo Form 组件提供了表单验证的功能,只需要通过 `rules` 属性传入约定的验证规则,并将 Form-Item 的 `prop` 属性设置为需校验的字段名即可。校验规则参见 [async-validator](https://github.com/yiminghe/async-validator)
```html ```html
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"> <el-form
:model="ruleForm"
:rules="rules"
ref="ruleForm"
label-width="100px"
class="demo-ruleForm"
>
<el-form-item label="活动名称" prop="name"> <el-form-item label="活动名称" prop="name">
<el-input v-model="ruleForm.name"></el-input> <el-input v-model="ruleForm.name"></el-input>
</el-form-item> </el-form-item>
@ -188,13 +215,22 @@ W3C 标准中有如下[规定](https://www.w3.org/MarkUp/html-spec/html-spec_8.h
<el-form-item label="活动时间" required> <el-form-item label="活动时间" required>
<el-col :span="11"> <el-col :span="11">
<el-form-item prop="date1"> <el-form-item prop="date1">
<el-date-picker type="date" placeholder="选择日期" v-model="ruleForm.date1" style="width: 100%;"></el-date-picker> <el-date-picker
type="date"
placeholder="选择日期"
v-model="ruleForm.date1"
style="width: 100%;"
></el-date-picker>
</el-form-item> </el-form-item>
</el-col> </el-col>
<el-col class="line" :span="2">-</el-col> <el-col class="line" :span="2">-</el-col>
<el-col :span="11"> <el-col :span="11">
<el-form-item prop="date2"> <el-form-item prop="date2">
<el-time-picker placeholder="选择时间" v-model="ruleForm.date2" style="width: 100%;"></el-time-picker> <el-time-picker
placeholder="选择时间"
v-model="ruleForm.date2"
style="width: 100%;"
></el-time-picker>
</el-form-item> </el-form-item>
</el-col> </el-col>
</el-form-item> </el-form-item>
@ -219,7 +255,9 @@ W3C 标准中有如下[规定](https://www.w3.org/MarkUp/html-spec/html-spec_8.h
<el-input type="textarea" v-model="ruleForm.desc"></el-input> <el-input type="textarea" v-model="ruleForm.desc"></el-input>
</el-form-item> </el-form-item>
<el-form-item> <el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button> <el-button type="primary" @click="submitForm('ruleForm')"
>立即创建</el-button
>
<el-button @click="resetForm('ruleForm')">重置</el-button> <el-button @click="resetForm('ruleForm')">重置</el-button>
</el-form-item> </el-form-item>
</el-form> </el-form>
@ -235,52 +273,73 @@ W3C 标准中有如下[规定](https://www.w3.org/MarkUp/html-spec/html-spec_8.h
delivery: false, delivery: false,
type: [], type: [],
resource: '', resource: '',
desc: '' desc: '',
}, },
rules: { rules: {
name: [ name: [
{ required: true, message: '请输入活动名称', trigger: 'blur' }, { required: true, message: '请输入活动名称', trigger: 'blur' },
{ min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' } {
min: 3,
max: 5,
message: '长度在 3 到 5 个字符',
trigger: 'blur',
},
], ],
region: [ region: [
{ required: true, message: '请选择活动区域', trigger: 'change' } { required: true, message: '请选择活动区域', trigger: 'change' },
], ],
date1: [ date1: [
{ type: 'date', required: true, message: '请选择日期', trigger: 'change' } {
type: 'date',
required: true,
message: '请选择日期',
trigger: 'change',
},
], ],
date2: [ date2: [
{ type: 'date', required: true, message: '请选择时间', trigger: 'change' } {
type: 'date',
required: true,
message: '请选择时间',
trigger: 'change',
},
], ],
type: [ type: [
{ type: 'array', required: true, message: '请至少选择一个活动性质', trigger: 'change' } {
type: 'array',
required: true,
message: '请至少选择一个活动性质',
trigger: 'change',
},
], ],
resource: [ resource: [
{ required: true, message: '请选择活动资源', trigger: 'change' } { required: true, message: '请选择活动资源', trigger: 'change' },
], ],
desc: [ desc: [
{ required: true, message: '请填写活动形式', trigger: 'blur' } { required: true, message: '请填写活动形式', trigger: 'blur' },
] ],
} },
}; }
}, },
methods: { methods: {
submitForm(formName) { submitForm(formName) {
this.$refs[formName].validate((valid) => { this.$refs[formName].validate(valid => {
if (valid) { if (valid) {
alert('submit!'); alert('submit!')
} else { } else {
console.log('error submit!!'); console.log('error submit!!')
return false; return false
} }
}); })
}, },
resetForm(formName) { resetForm(formName) {
this.$refs[formName].resetFields(); this.$refs[formName].resetFields()
} },
} },
} }
</script> </script>
``` ```
::: :::
### 自定义校验规则 ### 自定义校验规则
@ -288,13 +347,29 @@ W3C 标准中有如下[规定](https://www.w3.org/MarkUp/html-spec/html-spec_8.h
这个例子中展示了如何使用自定义验证规则来完成密码的二次验证。 这个例子中展示了如何使用自定义验证规则来完成密码的二次验证。
:::demo 本例还使用`status-icon`属性为输入框添加了表示校验结果的反馈图标。 :::demo 本例还使用`status-icon`属性为输入框添加了表示校验结果的反馈图标。
```html ```html
<el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"> <el-form
:model="ruleForm"
status-icon
:rules="rules"
ref="ruleForm"
label-width="100px"
class="demo-ruleForm"
>
<el-form-item label="密码" prop="pass"> <el-form-item label="密码" prop="pass">
<el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input> <el-input
type="password"
v-model="ruleForm.pass"
autocomplete="off"
></el-input>
</el-form-item> </el-form-item>
<el-form-item label="确认密码" prop="checkPass"> <el-form-item label="确认密码" prop="checkPass">
<el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input> <el-input
type="password"
v-model="ruleForm.checkPass"
autocomplete="off"
></el-input>
</el-form-item> </el-form-item>
<el-form-item label="年龄" prop="age"> <el-form-item label="年龄" prop="age">
<el-input v-model.number="ruleForm.age"></el-input> <el-input v-model.number="ruleForm.age"></el-input>
@ -309,76 +384,71 @@ W3C 标准中有如下[规定](https://www.w3.org/MarkUp/html-spec/html-spec_8.h
data() { data() {
var checkAge = (rule, value, callback) => { var checkAge = (rule, value, callback) => {
if (!value) { if (!value) {
return callback(new Error('年龄不能为空')); return callback(new Error('年龄不能为空'))
} }
setTimeout(() => { setTimeout(() => {
if (!Number.isInteger(value)) { if (!Number.isInteger(value)) {
callback(new Error('请输入数字值')); callback(new Error('请输入数字值'))
} else { } else {
if (value < 18) { if (value < 18) {
callback(new Error('必须年满18岁')); callback(new Error('必须年满18岁'))
} else { } else {
callback(); callback()
} }
} }
}, 1000); }, 1000)
}; }
var validatePass = (rule, value, callback) => { var validatePass = (rule, value, callback) => {
if (value === '') { if (value === '') {
callback(new Error('请输入密码')); callback(new Error('请输入密码'))
} else { } else {
if (this.ruleForm.checkPass !== '') { if (this.ruleForm.checkPass !== '') {
this.$refs.ruleForm.validateField('checkPass'); this.$refs.ruleForm.validateField('checkPass')
} }
callback(); callback()
} }
}; }
var validatePass2 = (rule, value, callback) => { var validatePass2 = (rule, value, callback) => {
if (value === '') { if (value === '') {
callback(new Error('请再次输入密码')); callback(new Error('请再次输入密码'))
} else if (value !== this.ruleForm.pass) { } else if (value !== this.ruleForm.pass) {
callback(new Error('两次输入密码不一致!')); callback(new Error('两次输入密码不一致!'))
} else { } else {
callback(); callback()
} }
}; }
return { return {
ruleForm: { ruleForm: {
pass: '', pass: '',
checkPass: '', checkPass: '',
age: '' age: '',
}, },
rules: { rules: {
pass: [ pass: [{ validator: validatePass, trigger: 'blur' }],
{ validator: validatePass, trigger: 'blur' } checkPass: [{ validator: validatePass2, trigger: 'blur' }],
], age: [{ validator: checkAge, trigger: 'blur' }],
checkPass: [ },
{ validator: validatePass2, trigger: 'blur' } }
],
age: [
{ validator: checkAge, trigger: 'blur' }
]
}
};
}, },
methods: { methods: {
submitForm(formName) { submitForm(formName) {
this.$refs[formName].validate((valid) => { this.$refs[formName].validate(valid => {
if (valid) { if (valid) {
alert('submit!'); alert('submit!')
} else { } else {
console.log('error submit!!'); console.log('error submit!!')
return false; return false
} }
}); })
}, },
resetForm(formName) { resetForm(formName) {
this.$refs[formName].resetFields(); this.$refs[formName].resetFields()
} },
} },
} }
</script> </script>
``` ```
::: :::
:::tip :::tip
@ -388,8 +458,14 @@ W3C 标准中有如下[规定](https://www.w3.org/MarkUp/html-spec/html-spec_8.h
### 动态增减表单项 ### 动态增减表单项
:::demo 除了在 Form 组件上一次性传递所有的验证规则外还可以在单个的表单域上传递属性的验证规则 :::demo 除了在 Form 组件上一次性传递所有的验证规则外还可以在单个的表单域上传递属性的验证规则
```html ```html
<el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="100px" class="demo-dynamic"> <el-form
:model="dynamicValidateForm"
ref="dynamicValidateForm"
label-width="100px"
class="demo-dynamic"
>
<el-form-item <el-form-item
prop="email" prop="email"
label="邮箱" label="邮箱"
@ -409,10 +485,13 @@ W3C 标准中有如下[规定](https://www.w3.org/MarkUp/html-spec/html-spec_8.h
required: true, message: '域名不能为空', trigger: 'blur' required: true, message: '域名不能为空', trigger: 'blur'
}" }"
> >
<el-input v-model="domain.value"></el-input><el-button @click.prevent="removeDomain(domain)">删除</el-button> <el-input v-model="domain.value"></el-input
><el-button @click.prevent="removeDomain(domain)">删除</el-button>
</el-form-item> </el-form-item>
<el-form-item> <el-form-item>
<el-button type="primary" @click="submitForm('dynamicValidateForm')">提交</el-button> <el-button type="primary" @click="submitForm('dynamicValidateForm')"
>提交</el-button
>
<el-button @click="addDomain">新增域名</el-button> <el-button @click="addDomain">新增域名</el-button>
<el-button @click="resetForm('dynamicValidateForm')">重置</el-button> <el-button @click="resetForm('dynamicValidateForm')">重置</el-button>
</el-form-item> </el-form-item>
@ -422,26 +501,28 @@ W3C 标准中有如下[规定](https://www.w3.org/MarkUp/html-spec/html-spec_8.h
data() { data() {
return { return {
dynamicValidateForm: { dynamicValidateForm: {
domains: [{ domains: [
value: '' {
}], value: '',
email: '' },
} ],
}; email: '',
},
}
}, },
methods: { methods: {
submitForm(formName) { submitForm(formName) {
this.$refs[formName].validate((valid) => { this.$refs[formName].validate(valid => {
if (valid) { if (valid) {
alert('submit!'); alert('submit!')
} else { } else {
console.log('error submit!!'); console.log('error submit!!')
return false; return false
} }
}); })
}, },
resetForm(formName) { resetForm(formName) {
this.$refs[formName].resetFields(); this.$refs[formName].resetFields()
}, },
removeDomain(item) { removeDomain(item) {
var index = this.dynamicValidateForm.domains.indexOf(item) var index = this.dynamicValidateForm.domains.indexOf(item)
@ -452,20 +533,27 @@ W3C 标准中有如下[规定](https://www.w3.org/MarkUp/html-spec/html-spec_8.h
addDomain() { addDomain() {
this.dynamicValidateForm.domains.push({ this.dynamicValidateForm.domains.push({
value: '', value: '',
key: Date.now() key: Date.now(),
}); })
} },
} },
} }
</script> </script>
``` ```
::: :::
### 数字类型验证 ### 数字类型验证
:::demo 数字类型的验证需要在 `v-model` 处加上 `.number` 的修饰符,这是 `Vue` 自身提供的用于将绑定值转化为 `number` 类型的修饰符。 :::demo 数字类型的验证需要在 `v-model` 处加上 `.number` 的修饰符,这是 `Vue` 自身提供的用于将绑定值转化为 `number` 类型的修饰符。
```html ```html
<el-form :model="numberValidateForm" ref="numberValidateForm" label-width="100px" class="demo-ruleForm"> <el-form
:model="numberValidateForm"
ref="numberValidateForm"
label-width="100px"
class="demo-ruleForm"
>
<el-form-item <el-form-item
label="年龄" label="年龄"
prop="age" prop="age"
@ -474,10 +562,16 @@ W3C 标准中有如下[规定](https://www.w3.org/MarkUp/html-spec/html-spec_8.h
{ type: 'number', message: '年龄必须为数字值'} { type: 'number', message: '年龄必须为数字值'}
]" ]"
> >
<el-input type="age" v-model.number="numberValidateForm.age" autocomplete="off"></el-input> <el-input
type="age"
v-model.number="numberValidateForm.age"
autocomplete="off"
></el-input>
</el-form-item> </el-form-item>
<el-form-item> <el-form-item>
<el-button type="primary" @click="submitForm('numberValidateForm')">提交</el-button> <el-button type="primary" @click="submitForm('numberValidateForm')"
>提交</el-button
>
<el-button @click="resetForm('numberValidateForm')">重置</el-button> <el-button @click="resetForm('numberValidateForm')">重置</el-button>
</el-form-item> </el-form-item>
</el-form> </el-form>
@ -486,28 +580,29 @@ W3C 标准中有如下[规定](https://www.w3.org/MarkUp/html-spec/html-spec_8.h
data() { data() {
return { return {
numberValidateForm: { numberValidateForm: {
age: '' age: '',
} },
}; }
}, },
methods: { methods: {
submitForm(formName) { submitForm(formName) {
this.$refs[formName].validate((valid) => { this.$refs[formName].validate(valid => {
if (valid) { if (valid) {
alert('submit!'); alert('submit!')
} else { } else {
console.log('error submit!!'); console.log('error submit!!')
return false; return false
} }
}); })
}, },
resetForm(formName) { resetForm(formName) {
this.$refs[formName].resetFields(); this.$refs[formName].resetFields()
} },
} },
} }
</script> </script>
``` ```
::: :::
:::tip :::tip
@ -519,6 +614,7 @@ W3C 标准中有如下[规定](https://www.w3.org/MarkUp/html-spec/html-spec_8.h
通过设置 Form 上的 `size` 属性可以使该表单内所有可调节大小的组件继承该尺寸。Form-Item 也具有该属性。 通过设置 Form 上的 `size` 属性可以使该表单内所有可调节大小的组件继承该尺寸。Form-Item 也具有该属性。
:::demo 如果希望某个表单项或某个表单组件的尺寸不同于 Form 上的`size`属性,直接为这个表单项或表单组件设置自己的`size`即可。 :::demo 如果希望某个表单项或某个表单组件的尺寸不同于 Form 上的`size`属性,直接为这个表单项或表单组件设置自己的`size`即可。
```html ```html
<el-form ref="form" :model="sizeForm" label-width="80px" size="mini"> <el-form ref="form" :model="sizeForm" label-width="80px" size="mini">
<el-form-item label="活动名称"> <el-form-item label="活动名称">
@ -532,16 +628,28 @@ W3C 标准中有如下[规定](https://www.w3.org/MarkUp/html-spec/html-spec_8.h
</el-form-item> </el-form-item>
<el-form-item label="活动时间"> <el-form-item label="活动时间">
<el-col :span="11"> <el-col :span="11">
<el-date-picker type="date" placeholder="选择日期" v-model="sizeForm.date1" style="width: 100%;"></el-date-picker> <el-date-picker
type="date"
placeholder="选择日期"
v-model="sizeForm.date1"
style="width: 100%;"
></el-date-picker>
</el-col> </el-col>
<el-col class="line" :span="2">-</el-col> <el-col class="line" :span="2">-</el-col>
<el-col :span="11"> <el-col :span="11">
<el-time-picker placeholder="选择时间" v-model="sizeForm.date2" style="width: 100%;"></el-time-picker> <el-time-picker
placeholder="选择时间"
v-model="sizeForm.date2"
style="width: 100%;"
></el-time-picker>
</el-col> </el-col>
</el-form-item> </el-form-item>
<el-form-item label="活动性质"> <el-form-item label="活动性质">
<el-checkbox-group v-model="sizeForm.type"> <el-checkbox-group v-model="sizeForm.type">
<el-checkbox-button label="美食/餐厅线上活动" name="type"></el-checkbox-button> <el-checkbox-button
label="美食/餐厅线上活动"
name="type"
></el-checkbox-button>
<el-checkbox-button label="地推活动" name="type"></el-checkbox-button> <el-checkbox-button label="地推活动" name="type"></el-checkbox-button>
<el-checkbox-button label="线下主题活动" name="type"></el-checkbox-button> <el-checkbox-button label="线下主题活动" name="type"></el-checkbox-button>
</el-checkbox-group> </el-checkbox-group>
@ -570,81 +678,86 @@ W3C 标准中有如下[规定](https://www.w3.org/MarkUp/html-spec/html-spec_8.h
delivery: false, delivery: false,
type: [], type: [],
resource: '', resource: '',
desc: '' desc: '',
} },
}; }
}, },
methods: { methods: {
onSubmit() { onSubmit() {
console.log('submit!'); console.log('submit!')
} },
} },
}; }
</script> </script>
``` ```
::: :::
### Form Attributes ### Form Attributes
| 参数 | 说明 | 类型 | 可选值 | 默认值 | | 参数 | 说明 | 类型 | 可选值 | 默认值 |
|---------- |-------------- |---------- |-------------------------------- |-------- | | ----------------------- | ----------------------------------------------------------------------------------------- | --------------- | --------------------- | ------ |
| model | 表单数据对象 | object | | — | | model | 表单数据对象 | object | | |
| rules | 表单验证规则 | object | — | — | | rules | 表单验证规则 | object | — | — |
| inline | 行内表单模式 | boolean | — | false | | inline | 行内表单模式 | boolean | — | false |
| label-position | 表单域标签的位置,如果值为 left 或者 right 时,则需要设置 `label-width` | string | right / left / top | right | | label-position | 表单域标签的位置,如果值为 left 或者 right 时,则需要设置 `label-width` | string | right / left / top | right |
| label-width | 表单域标签的宽度,例如 '50px'。作为 Form 直接子元素的 form-item 会继承该值。支持 `auto`。 | string / number | — | — | | label-width | 表单域标签的宽度,例如 '50px'。作为 Form 直接子元素的 form-item 会继承该值。支持 `auto`。 | string / number | — | — |
| label-suffix | 表单域标签的后缀 | string | — | — | | label-suffix | 表单域标签的后缀 | string | — | — |
| hide-required-asterisk | 是否显示必填字段的标签旁边的红色星号 | boolean | — | false | | hide-required-asterisk | 是否显示必填字段的标签旁边的红色星号 | boolean | — | false |
| show-message | 是否显示校验错误信息 | boolean | — | true | | show-message | 是否显示校验错误信息 | boolean | — | true |
| inline-message | 是否以行内形式展示校验信息 | boolean | — | false | | inline-message | 是否以行内形式展示校验信息 | boolean | — | false |
| status-icon | 是否在输入框中显示校验结果反馈图标 | boolean | — | false | | status-icon | 是否在输入框中显示校验结果反馈图标 | boolean | — | false |
| validate-on-rule-change | 是否在 `rules` 属性改变后立即触发一次验证 | boolean | — | true | | validate-on-rule-change | 是否在 `rules` 属性改变后立即触发一次验证 | boolean | — | true |
| size | 用于控制该表单内组件的尺寸 | string | medium / small / mini | — | | size | 用于控制该表单内组件的尺寸 | string | medium / small / mini | — |
| disabled | 是否禁用该表单内的所有组件。若设置为 true则表单内组件上的 disabled 属性不再生效 | boolean | — | false | | disabled | 是否禁用该表单内的所有组件。若设置为 true则表单内组件上的 disabled 属性不再生效 | boolean | — | false |
### Form Methods ### Form Methods
| 方法名 | 说明 | 参数 | 方法名 | 说明 | 参数 |
|---------- |-------------- | -------------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
| validate | 对整个表单进行校验的方法,参数为一个回调函数。该回调函数会在校验结束后被调用,并传入两个参数:是否校验成功和未通过校验的字段。若不传入回调函数,则会返回一个 promise | Function(callback: Function(boolean, object)) | validate | 对整个表单进行校验的方法,参数为一个回调函数。该回调函数会在校验结束后被调用,并传入两个参数:是否校验成功和未通过校验的字段。若不传入回调函数,则会返回一个 promise | Function(callback: Function(boolean, object)) |
| validateField | 对部分表单字段进行校验的方法 | Function(props: array \| string, callback: Function(errorMessage: string)) | validateField | 对部分表单字段进行校验的方法 | Function(props: array \| string, callback: Function(errorMessage: string)) |
| resetFields | 对整个表单进行重置,将所有字段值重置为初始值并移除校验结果 | — | resetFields | 对整个表单进行重置,将所有字段值重置为初始值并移除校验结果 | — |
| clearValidate | 移除表单项的校验结果。传入待移除的表单项的 prop 属性或者 prop 组成的数组,如不传则移除整个表单的校验结果 | Function(props: array \| string) | scrollToField | 滚动到指定表单字段 | Function(prop: string) |
| clearValidate | 移除表单项的校验结果。传入待移除的表单项的 prop 属性或者 prop 组成的数组,如不传则移除整个表单的校验结果 | Function(props: array \| string) |
### Form Events ### Form Events
| 事件名称 | 说明 | 回调参数 |
|--------- |-------- |---------- | | 事件名称 | 说明 | 回调参数 |
| -------- | ---------------------- | ---------------------------------------------------------- |
| validate | 任一表单项被校验后触发 | 被校验的表单项 prop 值,校验是否通过,错误消息(如果存在) | | validate | 任一表单项被校验后触发 | 被校验的表单项 prop 值,校验是否通过,错误消息(如果存在) |
### Form-Item Attributes ### Form-Item Attributes
| 参数 | 说明 | 类型 | 可选值 | 默认值 | | 参数 | 说明 | 类型 | 可选值 | 默认值 |
|---------- |-------------- |---------- |-------------------------------- |-------- | | -------------- | -------------------------------------------------------------------------------------------------------- | --------------- | --------------------------------- | ------ |
| prop | 表单域 model 字段,在使用 validate、resetFields 方法的情况下,该属性是必填的 | string | 传入 Form 组件的 `model` 中的字段 | — | | prop | 表单域 model 字段,在使用 validate、resetFields 方法的情况下,该属性是必填的 | string | 传入 Form 组件的 `model` 中的字段 | — |
| label | 标签文本 | string | — | — | | label | 标签文本 | string | — | — |
| label-width | 表单域标签的的宽度,例如 '50px'。支持 `auto`| string / number | — | — | | label-width | 表单域标签的的宽度,例如 '50px'。支持 `auto` | string / number | — | — |
| required | 是否必填,如不设置,则会根据校验规则自动生成 | boolean | — | false | | required | 是否必填,如不设置,则会根据校验规则自动生成 | boolean | — | false |
| rules | 表单验证规则, 具体配置见下表, 更多内容参考[async-validator](https://github.com/yiminghe/async-validator) | object / array | — | — | | rules | 表单验证规则, 具体配置见下表, 更多内容参考[async-validator](https://github.com/yiminghe/async-validator) | object / array | — | — |
| error | 表单域验证错误信息, 设置该值会使表单验证状态变为`error`,并显示该错误信息 | string | — | — | | error | 表单域验证错误信息, 设置该值会使表单验证状态变为`error`,并显示该错误信息 | string | — | — |
| show-message | 是否显示校验错误信息 | boolean | — | true | | show-message | 是否显示校验错误信息 | boolean | — | true |
| inline-message | 以行内形式展示校验信息 | boolean | — | false | | inline-message | 以行内形式展示校验信息 | boolean | — | false |
| size | 用于控制该表单域下组件的尺寸 | string | medium / small / mini | — | | size | 用于控制该表单域下组件的尺寸 | string | medium / small / mini | — |
### Rules ### Rules
| 参数 | 说明 | 类型 | 可选值 | 默认值 |
| -------- | ----------------- | ------ | ---- | ---- | | 参数 | 说明 | 类型 | 可选值 | 默认值 |
| trigger | 验证触发方式 | string | blur / change | — | | ------- | ------------ | ------ | ------------- | ------ |
| trigger | 验证触发方式 | string | blur / change | — |
### Form-Item Slot ### Form-Item Slot
| name | 说明 |
|------|--------| | name | 说明 |
| — | Form Item 的内容 | | ----- | ---------------------------------------------- |
| label | 自定义标签,参数为 { label } | | — | Form Item 的内容 |
| error | 自定义表单校验信息的显示方式,参数为 { error } | | label | 自定义标签,参数为 { label } |
| error | 自定义表单校验信息的显示方式,参数为 { error } |
### Form-Item Methods ### Form-Item Methods
| 方法名 | 说明 | 参数 | 方法名 | 说明 | 参数 |
|---------- |-------------- | -------------- | ------------- | ---------------------------------------------------- | ---- |
| resetField | 对该表单项进行重置,将其值重置为初始值并移除校验结果 | — | | resetField | 对该表单项进行重置,将其值重置为初始值并移除校验结果 | — |
| clearValidate | 移除该表单项的校验结果 | — | | clearValidate | 移除该表单项的校验结果 | — |