Quantcast
Channel: かずきのBlog@hatena
Viewing all articles
Browse latest Browse all 1387

React + TypeScriptのredux-formでバリデーションを行う

$
0
0

redux-form作るときにvalidateパラメータに検証関数を追加すればOKです。

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import * as ReduxForm from 'redux-form';
import * as Redux from 'redux';
import{Provider} from 'react-redux';

interface MyFormFields {
    x: string;
    y: string;
}interface MyFormProps extends ReduxForm.ReduxFormProps {
    onSubmit: (data: MyFormFields) => void;
}class MyForm extends React.Component<MyFormProps, {}> {
    render() {const{
            handleSubmit,
            fields: {x, y}} = this.props;
        return (
            <form onSubmit={handleSubmit}>
                <div>
                    <input type='text'{...x} />{x.error && <span>{x.error}</span>}</div>
                <div>
                    <input type='text'{...y} />{y.error && <span>{y.error}</span>}</div>
                <input type='submit' />
            </form>
        );
    }}// 検証用関数function validateContent(values: MyFormFields) {var result = {} as MyFormFields;
    if (!values.x) {
        result.x = 'xを入力してね';
    }if (!values.y) {
        result.y = 'yを入力してね';
    }return result;
}const SampleForm = ReduxForm.reduxForm({
    form: 'sample',
    fields: ['x', 'y'],
    validate: validateContent // formを作るときに渡す})(MyForm);

const reducer = Redux.combineReducers({
    form: ReduxForm.reducer
});
const store = Redux.createStore(reducer);

function handle(e: MyFormFields) {alert(e.x + ', ' + e.y);
}

ReactDOM.render(
    <Provider store={store}>
        <SampleForm onSubmit={handle}/>
    </Provider>,
    document.getElementById('content'));

これで実行すると、以下のようにバリデーションが行われた感じで表示されます。因みにエラーにはx.errorみたいにしてアクセスできます。

f:id:okazuki:20160121124230p:plain


Viewing all articles
Browse latest Browse all 1387

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>