Я думаю, вы можете попробовать что-то вроде этого
// declare vars where you should, and add the vars you want to test in an object
let result = [];
let toTest= {
firstName = "adem",
lastName = "corona",
email: "adamcorons@gmai.com",
}
// declare this function to test your values
function testValue(){
Object.keys(toTest).map(key => {
if(!toTest[key]){
result.push(key);
}
}
}
// where you need, call your function to test your strings
testValue();
// in your result array you will have the keys of all the empty vars in your object
Примечание: если для проверки поля у вас есть несколько плагинов, таких как Yup (если Formik) или validate. js, которые отлично подходят для этого! посмотри ! https://validatejs.org/
РЕДАКТИРОВАТЬ: Изменен ответ на массив, чтобы вы могли получить все результаты. Я рекомендую вам установить результат как объект {key: errorMessage, ...}, чтобы вам было легче использовать его после (например: вызовите error.nameOfInput в вашей форме для отображения ошибки.
EDIT2 : С объектом результат будет выглядеть так
// declare vars where you should, and add the vars you want to test in an object
let error= {};
let toTest= {
firstName = "adem",
lastName = "corona",
email: "adamcorons@gmai.com",
}
// declare this function to test your values
function testValue(){
Object.keys(toTest).map(key => {
if(!toTest[key]){
error[key]={`${key} cannot be empty`};
}
}
}
// where you need, call your function to test your strings
testValue();
// in your render
<input name="firstName" ...props />
{error.firstName && <div className='error'>{error.firstName} </div> }