CF2-85: Added register form validation

This commit is contained in:
KharchenkoVladimir 2021-10-22 17:40:03 +05:00
parent aaa26161da
commit 2f6e2fbc4e

View File

@ -1,13 +1,16 @@
import { Card, Form, Input, Select, Button, notification } from 'antd'; import { Card, Form, Input, Select, Button, notification } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons' import { UserOutlined,
LockOutlined,
EyeInvisibleOutlined,
EyeTwoTone } from '@ant-design/icons'
import logo from '../images/logo_32.png' import logo from '../images/logo_32.png'
import Loader from '../components/Loader' import Loader from '../components/Loader'
import { useState } from 'react' import { useState } from 'react'
import { Link, useHistory } from "react-router-dom"; import { Link, useHistory } from "react-router-dom";
import { AuthService } from '../services/api/' import { AuthService } from '../services/api/'
const openNotificationError = (message, title) => { const openNotification = (message, type, title) => {
notification['error']({ notification[type]({
message: title||'Ошибка', message: title||'Ошибка',
description: message, description: message,
}); });
@ -22,9 +25,30 @@ const companies = [
{ name: "ООО «Газпромнефть-ННГ»", value: 4 } { name: "ООО «Газпромнефть-ННГ»", value: 4 }
]; ];
const showError = (isErrorVisible, errorObj) => {
if (isErrorVisible)
return Promise.reject(errorObj)
return Promise.resolve()
}
const getValidationRules = (isRequired, message, isErrorVisible, errorObj) => {
return [
{ required: isRequired, message: message },
() => ({
validator() {
return showError(isErrorVisible, errorObj)
}
})
]
}
export default function Register() { export default function Register() {
const [loader, setLoader] = useState(false); const [loader, setLoader] = useState(false);
const [isErrorVisible, setErrorVisible] = useState(false); const [isLengthErrorVisible, setIsLengthErrorVisible] = useState(false);
const [isPasswordLengthErrorVisible, setIsPasswordLengthErrorVisible] = useState(false);
const [isPasswordMismatchErrorVisible, setIsPasswordMismatchErrorVisible] = useState(false);
const [selectedCompanyId, setSelectedCompanyId] = useState(companies[0].value); const [selectedCompanyId, setSelectedCompanyId] = useState(companies[0].value);
const history = useHistory(); const history = useHistory();
const [form] = Form.useForm(); const [form] = Form.useForm();
@ -35,251 +59,128 @@ export default function Register() {
<Option key={line.value}>{line.name}</Option> <Option key={line.value}>{line.name}</Option>
)); ));
const checkFormErrors = (formData) => {
if(formData.login.length < 4 || formData.login.length > 50){
setIsLengthErrorVisible(true)
form.validateFields()
return true
}
if(formData.password.length < 4 || formData.password.length > 50) {
setIsPasswordLengthErrorVisible(true)
form.validateFields()
return true
}
if(formData.password !== formData.confirmPassword) {
setIsPasswordMismatchErrorVisible(true)
form.validateFields()
return true
}
return false
}
let handleRegister = async (formData) =>{ let handleRegister = async (formData) =>{
if(checkFormErrors(formData))
return
formData.idCompany = +selectedCompanyId formData.idCompany = +selectedCompanyId
setLoader(true) setLoader(true)
try{ try{
await AuthService.register(formData) await AuthService.register(formData)
setLoader(false) setLoader(false)
openNotificationError("Заявка на регистрацию отправлена. ") openNotification("Заявка на регистрацию отправлена.", 'success')
history.push("/login"); history.push("/login");
}catch(e){ }catch(e){
if(e.status === 400) openNotification(e.message, 'error')
openNotificationError(e.message)
console.error(`Error ${e}`) console.error(`Error ${e}`)
setErrorVisible(true)
form.validateFields()
setLoader(false) setLoader(false)
} }
} }
const showError = (isErrorVisible, errorObj) => { const createInput = (name, placeholder, isRequired, requiredValidationMessage, lengthValidationMessage) => {
if (isErrorVisible)
return Promise.reject(errorObj)
return Promise.resolve() const rules = getValidationRules(true, requiredValidationMessage,
isLengthErrorVisible, new Error(lengthValidationMessage))
return (
<Form.Item
name={name}
rules={isRequired ? rules : []}
>
<Input
placeholder={placeholder}
prefix={<UserOutlined />}
onChange={() => {
setIsLengthErrorVisible(false)
form.validateFields()
}}
/>
</Form.Item>
)
}
const createPasswordInput = (name, message, errorObj, isErrorVisible, setIsErrorVisible) => {
return (
<Form.Item
name={name}
rules={getValidationRules(true, message, isErrorVisible, errorObj)}
>
<Input.Password
placeholder='Подтверждение пароля'
iconRender={visible => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
prefix={<LockOutlined />}
onChange={() => {
setIsErrorVisible(false)
form.validateFields()
}}
/>
</Form.Item>
)
} }
return ( return (
<div className='login_page shadow'> <div className='login_page shadow'>
<Card title="Система мониторинга" className='shadow' bordered={true} style={{ width: 350 }} extra={logoIcon}> <Card title="Система мониторинга" className='shadow' bordered={true} style={{ width: 350 }} extra={logoIcon}>
<Form form={form} onFinish={handleRegister}> <Form form={form} onFinish={handleRegister}>
<Form.Item {createInput('login', 'Пользователь', true,
name="login" 'Пожалуйста, введите имя!',
rules={[ 'Допустимая длина логина от 3 до 50 символов!')}
{ required: true, message: 'Пожалуйста, введите имя!' }, {createPasswordInput('password', 'Пожалуйста, введите пароль!',
() => ({ new Error('Допускаются пароли от 3х до 50ти символов'),
validator() { isPasswordLengthErrorVisible, setIsPasswordLengthErrorVisible)}
return showError(isErrorVisible, new Error('Неправильные логин или пароль!')) {createPasswordInput('confirmPassword', 'Пожалуйста, введите пароль повторно!',
} new Error('Пароли не совпадают!'), isPasswordMismatchErrorVisible,
}) setIsPasswordMismatchErrorVisible)}
]} {createInput('name', 'Имя', false)}
> {createInput('surName', 'Фамилия', false)}
<Input {createInput('patronymic', 'Отчество',false)}
placeholder="Пользователь" {createInput('email', 'Отчество',false)}
prefix={<UserOutlined />} {createInput('phone', 'Номер телефона',false)}
onChange={() => {
setErrorVisible(false)
form.validateFields()
}}
/>
</Form.Item>
<Form.Item
name="password"
rules={[
{ required: true, message: 'Пожалуйста, введите пароль!' },
() => ({
validator() {
return showError(isErrorVisible)
}
})
]}
>
<Input.Password
placeholder='пароль'
prefix={<LockOutlined />}
onChange={() => {
setErrorVisible(false)
form.validateFields()
}}
/>
</Form.Item>
<Form.Item
name="confirmPassword"
rules={[
{ required: true, message: 'Пожалуйста, введите пароль повторно' },
() => ({
validator() {
return showError(isErrorVisible)
}
})
]}
>
<Input.Password
placeholder='Подтверждение пароля'
prefix={<LockOutlined />}
onChange={() => {
setErrorVisible(false)
form.validateFields()
}}
/>
</Form.Item>
<Form.Item
name="name"
rules={[
{ required: true, message: 'Пожалуйста, введите имя' },
() => ({
validator() {
return showError(isErrorVisible)
}
})
]}
>
<Input
placeholder='Имя'
prefix={<LockOutlined />}
onChange={() => {
setErrorVisible(false)
form.validateFields()
}}
/>
</Form.Item>
<Form.Item
name="surName"
rules={[
{ required: true, message: 'Пожалуйста, введите фамилию' },
() => ({
validator() {
return showError(isErrorVisible)
}
})
]}
>
<Input
placeholder='Фамилия'
prefix={<LockOutlined />}
onChange={() => {
setErrorVisible(false)
form.validateFields()
}}
/>
</Form.Item>
<Form.Item
name="patronymic"
rules={[
{ required: true, message: 'Пожалуйста, введите отчество' },
() => ({
validator() {
return showError(isErrorVisible)
}
})
]}
>
<Input
placeholder='Отчество'
prefix={<LockOutlined />}
onChange={() => {
setErrorVisible(false)
form.validateFields()
}}
/>
</Form.Item>
<Form.Item
name="email"
rules={[
{ required: true, message: 'Пожалуйста, введите email' },
() => ({
validator() {
return showError(isErrorVisible)
}
})
]}
>
<Input
placeholder='Email'
prefix={<LockOutlined />}
onChange={() => {
setErrorVisible(false)
form.validateFields()
}}
/>
</Form.Item>
<Form.Item
name="phone"
rules={[
{ required: true, message: 'Пожалуйста, введите номер телефона' },
() => ({
validator() {
return showError(isErrorVisible)
}
})
]}
>
<Input
placeholder='Номер телефона'
prefix={<LockOutlined />}
onChange={() => {
setErrorVisible(false)
form.validateFields()
}}
/>
</Form.Item>
<Form.Item <Form.Item
name="idCompany" name="idCompany"
initialValue={companies[0].name} initialValue={companies[0].name}
rules={[
{ required: true, message: 'Пожалуйста, выберите компанию' },
() => ({
validator() {
return showError(isErrorVisible)
}
})
]}
> >
<Select <Select
placeholder="Выберите компанию" placeholder="Выберите компанию"
className="filter-selector" className="m-0"
value={selectedCompanyId} value={selectedCompanyId}
onChange={setSelectedCompanyId} onChange={setSelectedCompanyId}
> >
{children} {children}
</Select> </Select>
</Form.Item> </Form.Item>
{createInput('position', 'Должность',false)}
<Form.Item
name="position"
rules={[
{ required: true, message: 'Пожалуйста, введите должность' },
() => ({
validator() {
return showError(isErrorVisible)
}
})
]}
>
<Input
placeholder='Должность'
prefix={<LockOutlined />}
onChange={() => {
setErrorVisible(false)
form.validateFields()
}}
/>
</Form.Item>
<Form.Item> <Form.Item>
<div className='register-button'> <div className='register-button'>
<Button type="primary" htmlType="submit"> <Button
type="primary"
htmlType="submit"
>
Зарегистрироваться Зарегистрироваться
</Button> </Button>
</div> </div>