Skip to content

Commit

Permalink
fix: validate before unRegister
Browse files Browse the repository at this point in the history
  • Loading branch information
SyMind committed Aug 5, 2023
1 parent 4ae614f commit 1f654cb
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
41 changes: 39 additions & 2 deletions packages/semi-ui/form/__test__/field.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import { Form, Select } from '../../index';
import { noop } from 'lodash';
import { func } from 'prop-types';
import { BASE_CLASS_PREFIX } from '../../../semi-foundation/base/constants';
import { sleep as baseSleep } from '../../_test_/utils/index';

Expand Down Expand Up @@ -459,6 +457,45 @@ describe('Form-field', () => {
expect(formApi.getError('text')).not.toBeUndefined();
});

it('validate before unRegister', async () => {
let formApi = null;

const Foo = () => (
<Form
initValues={{
text: 'semi'
}}
getFormApi={api => {
formApi = api;
}}
>
{({ formState }) => (
<>
{formState.values.text && (
<Form.Input
field="text"
rules={[
{ required: true },
]}
/>
)}
</>
)}
</Form>
)

const form = mount(<Foo />);
const event = { target: { value: '' } };
form.find(`.${BASE_CLASS_PREFIX}-input`).simulate('change', event);
await sleep(200);
form.update();

formApi.setValue('text', 'foo');
expect(await formApi.validate()).toEqual({
text: 'foo'
});
});

// TODO
// it('allowEmptyString', () => {});
// it('extraText')
Expand Down
12 changes: 12 additions & 0 deletions packages/semi-ui/form/hoc/withField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,12 @@ function withField<
setStatus('default');
};


const unmounted = useRef(false);
useEffect(() => () => {
unmounted.current = true;
}, []);

// Execute the validation rules specified by rules
const _validateInternal = (val: any, callOpts: CallOpts) => {
let latestRules = rulesRef.current || [];
Expand All @@ -196,6 +202,9 @@ function withField<
if (validatePromise.current !== rootPromise) {
return;
}
if (unmounted.current) {
return;
}
// validation passed
setStatus('success');
updateError(undefined, callOpts);
Expand All @@ -205,6 +214,9 @@ function withField<
if (validatePromise.current !== rootPromise) {
return;
}
if (unmounted.current) {
return;
}
let { errors, fields } = err;
if (errors && fields) {
let messages = errors.map((e: any) => e.message);
Expand Down

0 comments on commit 1f654cb

Please sign in to comment.