0

I am currently trying to make a login / create account page for a website that I am developing for fun. In the create account form, I have an input field for username, name, email, password, and verify password. I also have patterns in the input fields so that the user makes valid account info. Here is the form below:

<form  method="post" action="CreateAccount.php">
                        <h1>Create Account</h1>
                        <input class="inputInfo" type="text" name="username" id="newUsername" pattern="[A-Za-z0-9]+" placeholder="Username" maxlength="40" minlength="5" onkeyup="checkInput()" onblur="checkInput()" autocomplete="off" required/>
                        <input class="inputInfo" type="text" name="fullname" id="newName" placeholder="First and Last Name" onkeyup="checkInput()" onblur="checkInput()" minlength="3" autocomplete="off" required/>
                        <input class="inputInfo" type="email" name="email" id="newEmail" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$" title="Must be a real email" placeholder="Email" onkeyup="checkInput()" onblur="checkInput()" required/>
                        <input class="inputInfo" type="password" name="password" id="newPassword" pattern="(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$" placeholder="Password" 
                            title="Must be 8 or more characters with at least one number or special character, uppercase letter, and lowercase letter" onkeypress="checkInput()" onblur="checkInput()" required/>
                        <input class="inputInfo" type="password" name="verifypassword" id="verifyPass" pattern="(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$" placeholder="Verify Password" 
                            title="Must be 8 or more characters with at least one number or special character, uppercase letter, and lowercase letter" onkeypress="checkInput()" onblur="checkInput()" required/>
                        <span><label for="showp"><input type="checkbox" id="showp" onclick="showPassword()">Show Password</label></span>
                        <button type="submit" style="margin-top: 7px;" class="disabled" id="submitButton">Sign Up</button>
                        <p style="font-size: 10px;">By signing up, you agree to our Terms , Data Policy and Cookies Policy .</p>
                    </form>

For clarification: the username pattern requires you to have a username with only upper and lower case letters and numbers and must be at least 5 characters and at most 40 characters. The email requires you to input a valid email address pattern. And the password requires a password that is at least 8 characters and must have an uppercase and lowercase letter and a number or special character.

In the input fields, you will see that I have a function called during blur or keyup event that is called checkInput(). The purpose of the function is to ensure that the input fields have the necessary length before the submit button can be enabled:

function checkInput () 
        {
            let usernameLength = document.getElementById('newUsername').value.length;
            let nameLength =  document.getElementById('newName').value.length;
            let emailLength = document.getElementById('newEmail').value.length;
            let passwordLength = document.getElementById('newPassword').value.length;
            let verifyLength = document.getElementById('verifyPass').value.length;

            if (usernameLength >= 5 && nameLength > 0 && emailLength > 0 && passwordLength >= 8 && verifyLength >= 8)
            {
                document.getElementById('submitButton').disabled = false;
                const element = document.querySelector('#submitButton');
                if (element.classList.contains('disabled'))
                {
                    element.classList.remove('disabled');
                }
            }
            else
            {
                document.getElementById('submitButton').disabled = true;
                const addElement = document.querySelector('#submitButton');
                addElement.classList.add('disabled');
            }
        }

I also have the following CSS classes that either make the border and shadow of the input field green or red:

.validInput {
    border-color: #50c878;
    box-shadow: 0 0 5px #50c878;
}

.invalidInput {
    border-color: #ff0000;
    box-shadow: 0 0 5px #ff0000;
}

My problem is that I would like to add some javascript so that while the user is typing in their information into the form, the code checks to make sure their input matches the patterns that are stated in the input fields. If the input they are putting into the field is valid, I would like for the javascript to add the validInput class to the input field. If the input is invalid I would like to add the invalidInput class to the input field. I have no idea, though, how to go about having JavaScript check if the input follows the pattern.

I would also like to make it to where it checks if the input is valid every time the user has a change event.

Does anyone have any ideas on how to go about doing this?

2
  • You can do document.getElementById('newUsername').addEventListener("change", checkInput) and do this for the other inputs. Commented Dec 18, 2020 at 0:25
  • @sidc the change event only fires when the user "commits" the new value, such as removing focus from the input. The OP will want to use the input event instead, which is fired on every keystroke. Commented Dec 18, 2020 at 1:06

1 Answer 1

1

You can use the addEventListener function with 'change' parameter if you want your verification to run after the user leaves the field, or with 'input' parameter if you want the verification to run each time the user writes something in the text field. This should do it for you:

// If you want the verification to run when the user leaves the input.
document.getElementById('newUsername').addEventListener("change", checkInput);
// If you want the verification to run each time the user changes the input.
document.getElementById('newUsername').addEventListener("input", checkInput);

For the verification part, you can use regex. Create the verification functions first, (checks if the input is valid):

let check_username = (username)=>{
    let rx = /^[a-z0-9]{8,40}$/i; 
    return rx.test(username); // Checks if the username is only made of alphanumeric characters (case insentisive)
}

let check_password = (password)=>{
    let special_char = /[0-9!@#\$%\^\&*\)\(+=._-]/; // If you want more special characters add them inside the braces at the end (after the '=+._-')
    let upper_char = /[a-z]/;
    let lower_char = /[A-Z]/;
    return special_char.test(password) // Checks if the password contains a special character or a number
    && upper_char.test(password) // Checks if the password contains an upper case letter
    && lower_char.test(password) // Checks if the password contains a lower case letter
    && password.length>=8; // checks the password length
}

let check_email = (email)=>{
    let rx = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+$/;
    return rx.test(email); // Checks the mail format.
}

Then you can use them like that:

check_username(document.getElementById('newUsername').value)
// This should return true if the username is valid or false if not.

Hope this was helpful. You can close the subject if that's what you are looking for.

Sign up to request clarification or add additional context in comments.

2 Comments

That works great for calling the function. Do you know how to go about having JS check if the input field follows the pattern criteria from the HTML though?
I edited the code, i hope this is what you are looking for

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.