In Let the Browser Check the Form, you put required, min, and max on Sam’s two boxes. Now the browser checks them every time the form is sent. It shows its bubble on the first box that fails, and it fires submit only after every check passes. Your input:user-invalid rule turns a box red after Sam has touched it.
One rule is still missing. Sam often forgets what’s already on the list and adds eggs a second time. In this lesson, you’ll write that rule in JavaScript and hand it to the browser, so a duplicate triggers the same bubble and red border as other invalid values. You’ll also send the form from your own code without skipping the checks. Start by seeing the problem on the page.
Find an Item Already on the List
Before the browser can refuse a duplicate, your code has to spot one. Reload the page so the list is empty, then type eggs and 3, and click Add. Type eggs and 3 again, and click Add once more. The list now shows the same row twice:
eggs (3), produce, normaleggs (3), produce, normal
The constraints can’t stop this. Each one looks at a single box’s value, such as whether it’s empty or over 20. Whether eggs is a duplicate depends on the items array, and only your script knows what’s in it. So the first step is a function that checks the array.
Add this function to main.js, after render():
kitchen/main.js
function isOnList(name) {
const wanted = name.toLowerCase();
for (const item of items) {
if (item.name.toLowerCase() === wanted) {
return true;
}
}
return false;
}
The loop compares the name with each record’s name and returns true at the first match. If no record matches, the loop ends and the function returns false. Both sides go through the string method toLowerCase(), so Eggs and eggs count as the same item.