简体   繁体   中英

Adding 'onblur' to a validation form

I am quite new to javascript and am trying to make a validation form that validates once you click out of the input field. I have been trying out many different ways to add on blur to a current validating form which I have created.

How could I add on blur to my validation form? Thanks :)

function addFormValidation(theForm) {

    if (theForm === null || theForm.tagName.toUpperCase() !== 'FORM') {
        throw new Error("expected first parameter to addFormValidation to be a FORM.");
    }

    theForm.noValidate = true;

    theForm.addEventListener('submit', function(evt) {
        var isError = false;

        var elements = this.elements;
        for (var i = 0; i < elements.length; i += 1) {
            if (! isFieldValid(elements[i])) {
                isError = true;
            }
        }

        if (isError) {
            evt.preventDefault();
        }
    });

    function isFieldValid(field) {
        var errorMessage = "";

        if (! needsToBeValidated(field)) {
            return true;
        }

        if (field.id.length === 0 || field.name.length === 0) {
            console.error("error: ", field);
            throw new Error("found a field that is missing an id and/or name attribute. name should be there. id is required for determining the field's error message element.");
        }

        field.classList.remove('invalid');

        var errorSpan = document.querySelector('#' + field.id + '-error');

        if (errorSpan === null) {
            console.error("error: ", field);
            throw new Error("could not find the '#" + field.id + "-error' element. It's needed for error messages if #" + field.id + " is ever invalid.");
        }

        errorSpan.classList.remove('danger');
        errorSpan.innerHTML = "";

        if (field.minLength > 0 && field.value.length < field.minLength) {
            errorMessage = "Must be " + field.minLength + " or more characters long.";
        }

        if (field.type === "email" && !isEmail(field.value)) {
            errorMessage = "This should be a valid email address.";
        }

        if (field.required && field.value.trim() === "") {
            errorMessage = "This field is required.";
        }

        if (errorMessage !== "") {
            field.classList.add('invalid');

            errorSpan.classList.add('danger');
            errorSpan.innerHTML = errorMessage;
            return false;
        }

        return true;
    }

    function needsToBeValidated(field) {
        return ['submit', 'reset', 'button', 'hidden', 'fieldset'].indexOf(field.type) === -1;
    }

    function isEmail(input) {
        return input.match(/^([a-z0-9_.\-+]+)@([\da-z.\-]+)\.([a-z\.]{2,})$/);
    }
}

HTML

<div class="content">
<form id="contact-form" method="POST" action="success.html">

  <div class="form-group">
    <label for="firstname">First Name</label>
    <input id="firstname" type="text" name="firstname" value="" onblur="addFormValidation('firstname');"/>
    <span id="firstname-error"></span>
  </div>

  <div class="form-group">
    <label for="lastname">Last Name</label>
    <input id="lastname" type="text" name="lastname" onblur="addFormValidation('lastname');">
    <span id= "lastname-error" ></span>
  </div>

  <div class="form-group">
    <label for="email">Email Address</label>
    <input id="email" type="email" name="email" required>
    <span id="email-error"></span>
  </div>

              <div class="form-group">
    <label for="flight">Flight</label>
    <select name="flight" id="flight" required>
    <option value="">Please select a flight</option>
    <option value="1">Fixed Wing</option>
    <option value="2">Helicopter</option>
    <option value="3">Glider</option>
    </select>
    <span id="flight-error"></span>
  </div>



        <div class="form-group">
    <label for="date">Date</label>
    <input id="date" type="date" name="date" required>
    <span id="date-error"></span>
  </div>

        <div class="form-group">
    <label for="time">Time</label>
    <input id="time" type="time" name="time" required>
    <span id="time-error"></span>
  </div>

        <div class="form-group">
    <label for="duration">Duration</label>

    <select name="duration" id="duration" required>
    <option value="">Please select your desired duration</option>
    <option value="1">1 Hour</option>
    <option value="2">2 Hours</option>
    <option value="3">3 Hours</option>
    <option value="4">4 Hours</option>
    <option value="5">5 Hours</option>
    </select>
    <span id="duration-error"></span>
  </div>



  <div class="form-group">
    <button type="submit">Submit</button>
  </div>

</form>
</div>

<script>
  document.addEventListener('DOMContentLoaded', function() {
    addFormValidation(document.querySelector('#contact-form'));
  });
</script>

http://jsfiddle.net/dLz5w2tz/

I always recommend not using element attributes (onblur) for javascript event execution; instead you can add the listener to your javascript code.

I've done the following to your code:

  1. Remove "onblur" attributes
  2. Add code in your JS to listen to blur events on the entire form (all elements).

JS snipped

theForm.addEventListener('blur', function(evt) {
    console.log(evt);
}, true);

Updated JS Fiddle: http://jsfiddle.net/dLz5w2tz/1/

Note: addEventListner takes 3 parameters - 1. "event" 2. function to execute 3. boolean - should it bubble/propagate the event upwards.

So basically, in this code, the event takes place on the form element (input) and bubbles up to the form itself. You can verify this by looking at the event variable (evt).

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