验证失败后表单验证未重置

时间:2018-04-13 09:30:51

标签: javascript validation

我正在使用一个小脚本来验证邮政编码,该邮件有效并阻止用户输入无效密码,但是当输入无效的邮政编码时,您无法提交正确的条目。例如,如果我输入'ST',我收到消息告诉我邮政编码无效,所以如果不手动刷新页面,我输入'ST6 1SA'(这是一个有效的Stoke邮政编码),我不能提交表格,我只是不断收到无效的工具提示,告诉我邮政编码的格式不正确。

JS:

<script>
   // Validate the postcode before it's sent
   (function () {
      var postcode = document.getElementById('postcode-entry');
      var wrapper = document.getElementById('validation');
      var notify = document.createElement('div');
      var mnisLookup = document.getElementById('mnis-results');
      var matchingClients = document.getElementById('matching-clients');
      var postcodeWrapper = document.getElementById('postcode-wrapper');

      notify.id = 'notify';
      notify.style.display = 'none';
      wrapper.appendChild(notify);

      postcode.addEventListener('invalid', function (event) {
         if (!event.target.validity.valid) {
         notify.textContent = 'Please enter a valid postcode e.g. ST1, ST1 4BJ';
         notify.className = 'error';
         notify.style.display = 'block';

         postcode.className = 'form-control invalid';
      }                
   });
})();
</script>

HTML:

<form id="postcode-wrapper" class="form-horizontal">
        <div id="postcode-lookup" class="form-group">
            <label for="postcode-entry" class="col-sm-1">Postcode:</label>
            <div id="postcode-entry-wrapper" class="col-sm-3">
                <input type="text" pattern="^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y])))( {0,}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2})?))$" oninvalid="setCustomValidity('Invalid Post Code Format ')" class="form-control" id="postcode-entry" placeholder="Enter your postcode" name="Postcode" />
            </div>
            <div class="col-sm-1">
                <input id="search" type="submit" value="Search" class="btn btn-default" />
            </div>
            <div id="validation" class="col-sm-7"></div>
        </div>
    </form>

只是一个快速注释,可能会影响页面刷新的方式,这是在MVC Razor页面中并用Html.BeginForm包裹 - 不确定这是否有所作为?

1 个答案:

答案 0 :(得分:1)

调试代码时,我发现即使输入有效,import { CircularTabs } from "../../components/circular-tabs/circular-tabs"; export class MainPage { @ViewChild("myTabs") myTabs: Tabs; @ViewChild("myCircularTabs") circularTabs: CircularTabs; 也会返回false。 &#39; ST6 1SA&#39;。这是因为它没有更新新输入的自定义验证,并且即使在输入有效输入后,先前的状态仍然存在。

因此,要更新并重置之前的验证,您必须在输入更改时重置event.target.validity.valid,即setCustomValidity('')

请替换此代码:

oninput="setCustomValidity('')"
相关问题