繁体   English   中英

在验证表单中添加“模糊”

[英]Adding 'onblur' to a validation form

我对javascript很陌生,并且正在尝试制作一个验证表单,一旦您从输入字段中单击鼠标,它就会进行验证。 我一直在尝试许多不同的方法来将模糊添加到当前创建的验证表单中。

如何在验证表单上添加模糊内容? 谢谢 :)

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/

我总是建议不要将元素属性(onblur)用于javascript事件执行; 相反,您可以将侦听器添加到您的JavaScript代码中。

我对您的代码执行了以下操作:

  1. 删除“ onblur”属性
  2. 在您的JS中添加代码以侦听整个表单(所有元素)上的模糊事件。

JS剪断

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

更新了JS Fiddle: http : //jsfiddle.net/dLz5w2tz/1/

注意:addEventListner需要3个参数-1.“事件” 2.要执行的函数3.布尔值-如果它向上冒泡/传播事件。

因此,基本上,在这段代码中,事件发生在表单元素(输入)上,并冒泡到表单本身。 您可以通过查看事件变量(evt)进行验证。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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