I have created a form and connected it to server.
JavaScript
x
44
44
1
<form>
2
<h2>Create Account</h2>
3
4
<fieldset>
5
<label for="name">Username</label>
6
<input
7
onChange={(e) => handle(e)}
8
value={data.name}
9
type="text"
10
id="name"
11
name="name"
12
/>
13
14
<label for="email">Email</label>
15
<input
16
onChange={(e) => handle(e)}
17
value={data.email}
18
type="email"
19
id="email"
20
name="email"
21
/>
22
23
<label for="password">Password</label>
24
<input
25
onChange={(e) => handle(e)}
26
value={data.password}
27
type="text"
28
id="password"
29
name="password"
30
/>
31
<label for="confirmPassword">Confirm Password</label>
32
<input
33
onChange={(e) => handle(e)}
34
value={data.confirmPassword}
35
type="text"
36
id="confirmPassword"
37
name="confirmPassword"
38
/>
39
</fieldset>
40
<button type="submit" onClick={(e) => sendData(e)}>
41
Create Account
42
</button>
43
</form>
44
In case of validation error response is like this “message”: “ValidationError: confirmPassword: Confirm Password did not match“
By regular expression I can pic up the error from this message e.g. “Confirm password did not match“.
I don’t know how to show this error below respective input field ?
Advertisement
Answer
- In reducer, you should create the validation function
JavaScript
1
28
28
1
const reducer = combineReducers({
2
form: formReducer.validation({
3
loginValidation: loginValidation,
4
})
5
})
6
7
const loginValidation = values => {
8
const errors = {}
9
if (!values.email) {
10
errors.email = 'Required'
11
} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$/i.test(values.email)) {
12
errors.email = 'Invalid email address'
13
}
14
15
if (!values.password) {
16
errors.age = 'Required'
17
}
18
19
if (!values.confirmPassword) {
20
errors.age = 'Required'
21
}
22
23
if (values.confirmPassword !== values.password) {
24
errors.age = 'Confirm Password did not match'
25
}
26
return errors
27
}
28
- In form component, you should do sth like
JavaScript
1
10
10
1
<div>
2
<label>Email</label>
3
<Field name="email" component={email =>
4
<div>
5
<input type="text" {email} placeholder="Email"/>
6
{email.touched && email.error && <span>{email.error}</span>}
7
</div>
8
}/>
9
</div>
10