Form Validation Error Checking in JavaScript
So, I was going through this video : https://www.youtube.com/watch?&v=4CeTFW4agRw - which talks about form validation in React, but is really general JavaScript form validation implemented in React.
It has a line of code val.length > 0 && (valid = false); which got me wondering since this is equivalent to
if (val.length > 0)
{
valid = false;
}
Full Code :
const formValid = ({formErrors, ...rest}) =>
{
let valid = true;
Object.values(formErrors).forEach(val =>
{
val.length > 0 && (valid = false);
});
Object.values(rest).forEach(val =>
{
val === null && (valid = false);
});
return valid;
}
form = {
firstName: "J",
lastName: "Smith",
email: "j.com",
password: "",
formErrors: {
firstName: "Min 3 characters required",
lastName: "",
email: "Invalid Email",
password: ""
}
};
let err = formValid(form);
console.log(err);
In the one-liner it uses a boolean check and sets valid to false if val.length > 0. This works because a AND operator (.) with a FALSE (or 0) equates to FALSE.
AND can be represented by a dot - ·, TRUE as 1 and FALSE as 0. In Logic gates, The statement "A ∧ B is true if A and B are both true; otherwise, it is false." In simple 1 and 0 :
1.1 = 1
1.0 = 0
In the expression val.length > 0 && (valid = false), val.length = 25 which is greater than 0 for the first item, formErrors.firstName - which makes val.length > 0 equal to true. That is ANDed to (valid = false) which is false.
val.length > 0 is true or 1
(valid = false) = false or 0
1 . 0 = 0 or false
About the author
- I am a web consultant from Navi Mumbai. Mainly dealt with LAMP stack, now into Django and getting into Laravel and Cloud. Founder of nerul.in and gaali.in
Comments
Join the discussionNo comments yet. Be the first to comment.





