-
Notifications
You must be signed in to change notification settings - Fork 4
/
Lab14(Validation).txt
86 lines (76 loc) · 2.33 KB
/
Lab14(Validation).txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import React, { useState } from "react";
import { useForm } from "react-hook-form";
function Customer() {
const [customer, _setCustomer] = useState({ name: "", code: "" });
const [customers, _setCustomers] = useState([]);
const { register,trigger, handleSubmit,formState: { errors,isValid } } = useForm({mode:'onChange'});
//trigger("name");
React.useEffect(() => {
(async () => {
const result = await trigger();
// const result = await trigger("lastName", { shouldFocus: true }); allowed to focus input
})();
console.log("Component loaded");
}, []);
const onFormSubmit = data =>{
setCustomers();
};
const onErrors = errors => console.error(errors);
const setCustomer = e => {
_setCustomer(prevState => ({
...prevState,
[e.target.name]: e.target.value
}));
};
const setCustomers = e => {
_setCustomers(prevState => (
[...prevState, customer]
));
_setCustomer(prevState => ({
...prevState,
name: "", code: ""
}));
};
return (
<div className="App">
<form onSubmit={handleSubmit(onFormSubmit,onErrors)}>
{errors.name&&errors.name.type}
{errors.name && <span>Field is required</span>}<br></br>
{errors.code && <span>code is required</span>}
Name :-
<input
{...register("name", { required: true })}
type="text"
name="name"
/><br></br>
Code :-
<input
{...register("code", { required:true, pattern: /^[A-Z]{1,3}$/ })}
type="text" name="code"
/><br/>
<input
value="Add"
type="submit"
disabled={!isValid}
/>
<table>
<thead>
<tr>
<td>name</td>
<td>code</td>
</tr>
</thead>
<tbody>
{customers.map((x,index) => (
<tr key={index}>
<td>{x.name}</td>
<td>{x.code}</td>
</tr>
))}
</tbody>
</table>
</form>
</div>
);
}
export default Customer;