我被要求编写函数来验证具有标题和描述输入的表单的数据
在下面的代码中,我使用 if
进行验证,但我的老师要求我将这些 if
转换为函数并组合它们。
validate = () => {
let titleError = '';
let descriptionError = '';
const { title, description } = this.state;
const trimTitle = title.trim();
if (trimTitle === '') titleError = 'The title cannot be empty';
if (title.length > 500)
titleError = 'The title cannot be longer than 500 characters';
if (description.length > 2000)
descriptionError =
'The description cannot be longer than 2000 characters';
if (titleError !== '' || descriptionError !== '') {
this.setState({ titleError, descriptionError });
return false;
}
return true;
};
我试过做这样的功能:
emptyTitle = ({ titleError }) => {
// let titleError = '';
const trimTitle = title.trim();
if (trimTitle === '') titleError = 'The title cannot be empty';
this.setState({ titleError });
};
maxTitleLength = ({ title }) => {
let titleError = '';
if (title.length > 500)
titleError = 'The title cannot be longer than 500 characters';
this.setState({ titleError });
};
但我不确定我的方法。拜托,我将非常感谢任何建议。
最佳答案
我认为您已被要求避免命令式控制流,R.cond
是封装if/else
逻辑的函数式方式。希望对您有所帮助。
const createValidator = (name, { min, max }) => R.cond([
[
// normalize and compare min-length
R.pipe(R.trim, R.length, R.gte(min)),
// eventually return error message
R.always(`${name} cannot be empty`)
],
[
// normalize and compare max-length
R.pipe(R.trim, R.length, R.lt(max)),
// eventually return error message
R.always(`${name} too long`)
],
// all good, no errors to display
[R.T, R.always(null)]
]);
// The following can be ignored,
// only needed as boilerplate to prove the example
const Test = () => {
const [title, setTitle] = React.useState('');
const [description, setDescription] = React.useState('');
const withValue = (cb) => R.pipe(R.pathOr('', ['target', 'value']), cb);
const isTitleValid = createValidator('Title', { min: 0, max: 500 });
const isDescriptionValid = createValidator('Description', { min: 0, max: 2000 });
return (
<form onSubmit={e => e.preventDefault()}>
<div className="form-group">
<input className="form-control" placeholder="Title" value={title} onChange={withValue(setTitle)} />
</div>
<div className="form-group">
<textarea className="form-control" placeholder="Description" onChange={withValue(setDescription)} value={description} />
</div>
<ul className="text-danger">
<li>{isTitleValid(title)}</li>
<li>{isDescriptionValid(description)}</li>
</ul>
</form>
);
};
ReactDOM.render(<Test />, document.querySelector('#test'));
form { margin: 1em 2em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js" integrity="sha256-xB25ljGZ7K2VXnq087unEnoVhvTosWWtqXB4tAtZmHU=" crossorigin="anonymous"></script>
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<div id=test></div>
关于javascript - 如何编写验证函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57438723/