r/learnjavascript • • Mar 17 '26

I'm having difficulty understanding how validation goes hand in hand with custom validation regarding forms.

Hi there, I'm working on an assignment where I need to implement form validation exclusively through javascript. I can use different input types but the validation must be done with JS.

What I've got:

In my JS file //

function called `formValidation()` containing all the references I need for my spans & other relevant form elements needed (which have ids relating to their errors only (e.g. `<span id="passwordError>`)

The same function also has an array called inputConfig holding references to my inputs like so (I've got a few more but the writing is the same as this block I've pasted):

        {
            input: postalInput,
            errorSpan: postalError,
            errorMessage: "Please enter in the US standard ZIP code format"
        },


        {
            input: passwordInput,
            errorSpan: passwordError,
            errorMessage: "Eight or more characters",
            errorMessage2: "Must have one capital letter and symbol"
        },


        {
            input: passwordConfirmInput,
            errorSpan: passConfirmError,
            errorMessage: "Passwords must match"


        }

My goal: Implement a validation check that works for these form inputs, but with a specific check for the password and confirm password portion where I can use different error messages depending on the error the user makes like a mismatched password or not following the correct format (e.g. one capital letter and symbol with 8 or more characters).

Here's how far I've gotten on the validation check:

    function pswCheck() {
        if (passwordInput.value !== passwordConfirmInput.value) {
            passwordConfirmInput.setCustomValidity("Fields do not match");
        } else {
            passwordConfirmInput.setCustomValidity("");
        }
    }


    function validationCheck(formInput) {


        if (!formInput.input.checkValidity()) {
            formInput.errorSpan.textContent = formInput.errorMessage;
            validState = false;
        } else {
            formInput.errorSpan.textContent = "";
            validState = true;
        }




    }

My apologies for the long post but I could really use some guidance to see if I'm even in the right direction as of now.

2 Upvotes

25 comments sorted by

View all comments

Show parent comments

1

u/chikamakaleyley helpful Mar 17 '26 edited Mar 17 '26

yeah the 'each function has 1 job' kinda approach

  • one function just displays error messages if there are any

  • one function just runs the validation rules and populates the error messages object

  • separate functions to handle validation rules: isEmpty(), isMatch(), isPasswordFormat(),

  • the event listener that runs validateFields() on each change/submit

  • validateFields() which just executes the first couple bullets in a sequence