简体   繁体   English

表单验证集自定义有效性

[英]Form Validation Set Custom Validity

I'm playing around with form validations.我在玩表单验证。 I've build a simple captcha field and I want to check it via javascript.我已经建立了一个简单的验证码字段,我想通过 javascript 检查它。

At this point it works static.在这一点上它是静态的。 I need to add an eventlistener, but don't know how.我需要添加一个事件侦听器,但不知道如何添加。

Hope, you can help.希望,你能帮忙。

HTML HTML

<form>
  <input type="text" id="field_robot" name="">
  <input type="submit" id="submit" name="submit">
</form>

JS JS

var val = document.getElementById('field_robot').value;
var field = document.getElementById('field_robot');

field.addEventListener('input', function(){
  if (val != '42') {
    field.setCustomValidity('invalid');
  } 
}); 

The issue is you're declaring val outside of your event listener.问题是您在事件侦听器之外声明了val So, your value is never refreshed after the input.因此,您的值在输入后永远不会刷新。 You need to retrieve the field's value inside the event listener.您需要在事件侦听器中检索字段的值。

See the snippet below :请参阅下面的片段:

 var field = document.getElementById('field_robot'); field.addEventListener('input', function() { var val = document.getElementById('field_robot').value; if (val != '42') { field.setCustomValidity('invalid'); } else { event.target.setCustomValidity(''); } });
 <form id="myForm"> <input type="text" id="field_robot" name=""> <input type="submit" id="submit" name="submit"> </form>

Now, you can go a bit further and have a listener you could use for several input fields, using the event object provided by the listener and a fieldValidator function that would take your event and a boolean condition as parameters.现在,您可以更进一步,拥有一个可用于多个输入字段的侦听器,使用侦听器提供的event对象和一个fieldValidator函数,该函数将您的事件和布尔条件作为参数。

See this other snippet :看到这个其他片段:

 var field = document.getElementById('field_robot'); field.addEventListener('input', function(event) { fieldValidator(event, (field.value == '42')); }); function fieldValidator(event, condition) { var val = event.target.value; if (!condition) { event.target.setCustomValidity('invalid'); } else { event.target.setCustomValidity(''); } }
 <form id="myForm"> <input type="text" id="field_robot" name=""> <input type="submit" id="submit" name="submit"> </form>

So now it works well.所以现在它运作良好。

  var field = document.getElementById('field_robot');

  field.addEventListener('change', function() {
  var val = document.getElementById('field_robot').value;
  if (val != '42') {
    field.setCustomValidity('invalid');
  } else {
    field.setCustomValidity('');
  };
});

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

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