[英](required) in my react.js form doesn't work
我是編程新手,在我的 react.js 應用程序中,我試圖通過表單和我的表單從用戶那里獲取信息,我將required放在 form.control 中以確保輸入不為空並且在發送之前是必需的,但它不再起作用,即使表單為空也會發送
這是我的代碼,有什么辦法可以在表單中進行一些驗證嗎?
export default function AddCourse() {
const handleChange = (e) => {
e.preventDefault();
const { name, value } = e.target;
setCourseData({ ...courseData, [name]: value });
console.log(courseData);
};
const handleFileChange = (e) => {
const { name, files } = e.target;
setCourseData({ ...courseData, [name]: files[0] });
};
const submitForm = () => {
let form_data = new FormData();
form_data.append('user', userId);
form_data.append('category', courseData.category);
form_data.append('name', courseData.name);
form_data.append('brief', courseData.brief);
form_data.append('image', courseData.image);
try {
axios.post(baseUrl + '/course/', form_data,
).then((response) => {
// window.location.href='/AddCoursePage'; //to reload the page when the course added
if (response.status == 201) {
const Swal = require('sweetalert2');
Swal.fire(
'Good job!',
'Course has been added successfully',
'success'
)}
});
} catch (error) {
console.log(error);
}
};
return (
<Fragment>
<div className='Pro-bg'>
<div className='container mt-4'>
<Row>
<section className='col-md-9'>
<div className='card'>
<h5 className='card-header' >Add Course </h5>
<div className='card-body'>
<>
<Form >
<Form.Select className="mb-3" aria-label="Default select example" onChange={handleChange} name='category' required >
{category.map((category, index) => {
return <option key={index} value={category.id} > {category.title} </option>
})}
</Form.Select>
<FloatingLabel controlId="floatingTextarea" label="Course title" className="mb-3">
<Form.Control name='name' type="Text" placeholder="Leave a course decription here" onChange={handleChange} required />
</FloatingLabel>
<FloatingLabel controlId="floatingTextarea2" label="Leave a course decription here">
<Form.Control
name='brief'
required
type="Text"
placeholder="Leave a comment here"
onChange={handleChange}
style={{ height: '100px' }}
/>
</FloatingLabel>
<Form.Group controlId="formFileMultiple" className="mb-3 mt-3">
<Form.Control name='image' type="file" multiple onChange={handleFileChange} required />
</Form.Group>
</Form>
<Button blocksize="lg" variant="warning" type="submit" active onClick={submitForm} > Submit </Button>
</>
</div>
</div>
</section>
</Row>
</div>
</div>
</Fragment>
)
}
請任何幫助?
嘗試添加 boolean:
required={true}
Boolean,如果為真,則表示輸入必須有值才能提交表單。 您可以分配一個字符串以在錯誤 object 中返回錯誤消息。
import Swal from 'sweetalert2'
export default function AddCourse() {
const handleChange = (e) => {
e.preventDefault();
const { name, value } = e.target;
setCourseData({ ...courseData, [name]: value });
console.log(courseData);
}; // ...rest of your code
並從您的代碼中刪除它 const Swal = require('sweetalert2');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.