简体   繁体   中英

Form validation on blur

I have 5 input fields and I want them to validate on blur, and show either an error or success message, but through DOM scripting and not with an alert box. I've tried several different codes, even just small bits and pieces to see if it's correctly interacting with my html but it doesn't seem to work. So far, I have a small code to test if it even runs, and it's supposed to show an alert box but it does not. I would prefer to not use any innerHTML and use all functions within the javascript only. My html:

<div id=fNID>
                <label for="firstNameID">First Name: </label>
                <input id="firstNameID" type="text" name="firstNameA" value="" />
                <span> </span>
            </div>

            <div id=lNID>
                <label for="lastNameID">Last Name: </label>
                <input id="lastNameID" type="text" name="lastNameA" value="" />
                <span> </span>
            </div>

My javascript:


    firstNameID = document.surveyForm.getElementById("firstNameID");
    document.surveyForm.getElementById(fN).addEventListener("blur", validateName);
    function validateName() {
        var nameRegEx = /[a-zA-Z]+/;
        var firstNameID = document.getElementById("firstNameID");

        if (fN.matches(nameRegEx)) {
            alert("Success!")
        } else {
            alert("error")
        }
    }


    window.addEventListener("load", setupForm, false);
}

Bootstrap has a nice pattern for input validation . They use divs following the input: one for valid input, one for invalid input, making the appropriate one visible:

<div class="form-group">
    <label for="uname">Username:</label>
    <input class="form-control" id="uname">
    <div class="valid-feedback">Valid.</div>
    <div class="invalid-feedback">Please fill out this field.</div>
</div>

Bootstrap's CSS classes modify the display based on the input's pseudo-classes :valid and :invalid .

You can set these pseudo-classes in JavaScript with the setCustomValidity() method.

input.setCustomValidity("input is invalid")

will assign the :invalid pseudo-class to the input.

input.setCustomValidity("")

will assign the :valid pseudo class.

A working example:

 const input = document.getElementById('uname'); function makeValid() { input.setCustomValidity(''); } function makeInvalid() { input.setCustomValidity('a problem'); }
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> <h3 class="m-2">Bootstrap input with validation</h3> <form class="was-validated mx-2"> <div class="form-group"> <label for="uname">Username (required):</label> <input type="text" class="form-control" id="uname" placeholder="Enter username" name="uname"> <div class="valid-feedback">Valid.</div> <div class="invalid-feedback">This field is invalid.</div> </div> </form> <div class="m-2"> <p>Use setCustomValidity() to change input state:</p> <button onclick="makeValid();">:valid</button> <button onclick="makeInvalid();">:invalid</button> </div>

It's also worth noting that most browsers have native support for displaying validation messages on inputs. Here's an example that doesn't use any Bootstrap features:

 const input = document.getElementById('uname'); function makeValid() { input.setCustomValidity(''); } function makeInvalid() { input.setCustomValidity('this is invalid'); }
 body { background-color: #aaa; }.m-2 { margin: .5rem; }.mt-5 { margin-top: 1rem; }
 <body> <h3 class="m-2">Generic input with validation</h3> <form class="mt-5"> <label for="uname">Username:</label> <input type="text" id="uname" placeholder="Enter username" name="uname"> <p>Use setCustomValidity() to change input state:</p> <button onclick="makeInvalid();">input:invalid</button> </form> <div class="m-2"> <button onclick="makeValid();">input:valid</button> </div> </body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM