Onto lecture. #7 of Building Form section, better way to display error messages?

Hi everyone!
I didn’t like the way mosh showed the error messages therefore I was looking for a way if could just place the messages right infront of the values we are providing for the validations e.g
minLenght : 3, message: 'The min length should be 3' how ever after reading the document setError I found that it’s possible to do so, so I did it like this

<input id="name" type="text" className="form-control"
              {...register("name", {
                required: {
                  value: true,
                  message: "You must provide a value",
                },
                minLength: {
                  value: 3,
                  message: "Mut be atleast 3 characters long",
                },
              })}
            />

and upon displaying an error message we could simply do

{errors.name && typeof errors.name?.message === "string" && (
                <p>{errors.name?.message}</p>
              )}
2 Likes

Thanks for the great tip! I used it and love it! Odd though… Before adding your code from above, I couldn’t get my messages to show up as Mosh implemented it. Instead, I was getting a popup canned message when clicking Submit. I never figured out what was supplying those popup validation messages.

And just to clarify what I meant by “popup canned message”… it was a popup overlay window that appeared partially overlapping the lower part of the name text box with what appeared to be a default error message. I don’t recall what the exact wordings were for those messages, but they were pertinent to the type of error and in this code we were just validating for the presence of a value and that it had a minimum length.

1 Like

I think that’s the default HTML5 validation handling. It’s also happening to me and I think is preventing the react hook validation from triggering. I’m quite new to web development and I’m wondering if there is a way to prevent this “default” validation wich can vary from browser to browser in favor of the one implemented with react hook?

1 Like

sorry, was typing it wrong, my bad :frowning:

Thanks, I also made another post where Mosh did it like we could only submit the form once the fields were valid, which I find very bad in terms of User Experience because If the user is unable to even submit the form without validation, how will they know what’s the validation set on each field. e.g nobody would know that we have set 10 characters as the minimum length for password
I’m finding it hard to absorb all this react concept one reason is that i am faily new

1 Like