Commit 17319145 authored by Ben Anderson's avatar Ben Anderson

Added form validations for product creation

parent 95104079
import React, { useState } from "react";
export default function ProductForm({ product }) {
const [form, setForm] = useState({
ProductForm.defaultProps = {
product: {
sku: "",
upc: "",
productName: "",
......@@ -11,16 +11,63 @@ export default function ProductForm({ product }) {
stock: 0,
productDescription: "",
productImage: "",
});
},
};
export default function ProductForm({ product }) {
const [form, setForm] = useState(product);
const [errors, setErrors] = useState([]);
const validate = () => {
setErrors([]);
const errs = [];
if (form.sku.length < 3) {
errs.push("SKU must be at least 3 characters");
}
if (form.upc.length < 3) {
errs.push("UPC must be at least 3 characters");
}
if (form.productName.length === 0) {
errs.push("Please enter a product name");
}
if (form.brand.length === 0) {
errs.push("Please enter a brand");
}
if (form.category.length === 0) {
errs.push("Please specify a category");
}
if (Number(form.price) <= 0) {
errs.push("Price must be greater than 0");
}
if (Number(form.stock) <= 0) {
errs.push("Stock must be greater than 0");
}
setErrors([...errs]);
};
const onSubmit = (e) => {
e.preventDefault();
validate();
if (errors.length === 0) {
// TODO send form to products API
console.log(form);
}
};
return (
<div class="container">
<div className="container mt-3">
{errors.length ? (
<ul className="list-group">
{errors.map((error, i) => (
<li key={i} className="list-group-item list-group-item-danger">
{error}
</li>
))}
</ul>
) : null}
<form onSubmit={onSubmit}>
<div className="row mt-3">
<div className="col">
......@@ -28,6 +75,7 @@ export default function ProductForm({ product }) {
SKU
</label>
<input
required
name="sku"
type="text"
className="form-control"
......@@ -41,6 +89,7 @@ export default function ProductForm({ product }) {
UPC
</label>
<input
required
name="upc"
type="text"
className="form-control"
......@@ -57,6 +106,7 @@ export default function ProductForm({ product }) {
Name
</label>
<input
required
name="productName"
type="text"
className="form-control"
......@@ -72,6 +122,7 @@ export default function ProductForm({ product }) {
Brand
</label>
<input
required
name="brand"
type="text"
className="form-control"
......@@ -85,6 +136,7 @@ export default function ProductForm({ product }) {
Category
</label>
<input
required
name="category"
type="text"
className="form-control"
......@@ -117,6 +169,7 @@ export default function ProductForm({ product }) {
Price
</label>
<input
required
name="price"
type="number"
className="form-control"
......@@ -130,6 +183,7 @@ export default function ProductForm({ product }) {
Stock
</label>
<input
required
name="stock"
type="number"
className="form-control"
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment