В настоящее время я использую эту библиотеку для проверки правильности ввода формы во внешнем интерфейсе ( здесь ), который отправляется мне через объект. Я храню их в своем состоянии и использую значения состояния правил, чтобы проверить это по отношению к отправляемым данным. Я пытаюсь использовать это, чтобы проверить, что массив, который я отправляю, действителен, но когда консоль регистрирует объект валидатора, кажется, что даже если мой массив пуст, не отображается errorCount
, кажется, что он равен 0.
Вот как я этого добиваюсь:
import React, { useState, useEffect } from 'react';
import Validator from 'validatorjs';
import FormScene from 'ms/scenes/FormScene';
import Base from 'ms/scenes/Base';
import CheckBox from 'ms/components/Form/CheckBox';
import Notification from 'ms/components/Notification';
import { post } from 'ms/services/api';
import { connect } from 'react-redux';
import styles from './styles.scss';
const Requirements = props => {
const [options, setOptions] = useState(null);
const [rules, setRules] = useState(null);
const [id, setId] = useState(null)
const [closeNotification, setCloseNotification] = useState(1);
const [loader, setLoader] = useState(1);
const [data, setData] = useState([]);
const requirements = {
'requirements.selection': data,
}
useEffect(() => {
if (props.state.rules !== null && props.state.rules !== undefined) {
setOptions(props.state.rules.rules.deal);
setTimeout(() => {
setLoader(0)
}, 1000)
}
if (options !== null && options !== undefined) {
setRules({'requirements.selection': options.workflow.rules['requirements.selection']})
}
if (props.state.id.id !== null && props.state.id.id !== undefined) {
setId(props.state.id.id);
}
}, [props.state, options])
const closeNotificationHandler = () => {
setCloseNotification(0);
}
const onChange = (e) => {
let currentData = data;
if (e.target.checked) {
setData([...currentData, e.target.name]);
} else {
const index = currentData.indexOf(e.target.name);
if (index > -1) {
currentData.splice(index, 1);
setData([...currentData]);
}
}
}
const submit = (e) => {
e.preventDefault();
let validation = new Validator(requirements, rules);
console.log(validation);
if (validation === true) {
post(`deal/${id}/workflow/requirements`, {}, {requirements: requirements})
.then(res => {
})
.catch(err => {
})
} else {
console.log('validation failed')
}
}
console.log(rules);
// console.log(requirements);
return (
<Base>
{closeNotification === 1 ?
<Notification
message="Dropbox folders created."
notificationStatus={1}
closeNotification={closeNotificationHandler}
/>
: null}
{loader === 1 ? <p>Loading...</p> :
options.workflow.form.map(item => (
<FormScene key={item.name} title={item.value} onSubmit={submit}>
{item.components.map(item => (item.options.map(option =>
<CheckBox
key={option.name}
id={option.name}
name={item.field}
label={option.value}
val={option.value}
onChange={e => onChange(e)}
/>
)))}
</FormScene>
))
}
</Base>
)
}
const mapStateToProps = (state) => {
return {
state
}
}
export default connect(mapStateToProps)(Requirements);
На изображении клавиша input
соответствует requirements
в параметрах валидатора и rules
соответствуют параметру rules
.
Любая помощь приветствуется.