【问题标题】:Materialize css modal validation物化 css 模态验证
【发布时间】:2020-09-17 19:46:01
【问题描述】:

我正在使用 Materialize css 来设计我的帖子。假设我有一个模态表单并将其发布到服务器。 在该表单中,我正在检查是否所有字段都具有价值。

<form>
            <div class="input-field">
                <input type="text" id="title"  class="validate" required="" aria-required="true">
                <label for="title">Title</label>
            </div>

标题字段是必需的。但是,当我单击模式中的提交按钮时,即使标题字段具有空值,它也会关闭。有什么方法可以在 Materialize css v1 中保持模式打开以进行验证错误。

【问题讨论】:

  • 不要在点击时提交表单 - 有一个运行一些验证的按钮,然后如果成功,提交表单并关闭模式。
  • 你能给我一些工作的例子吗?

标签: css materialize


【解决方案1】:

考虑这个是在不同的步骤中。表单提交仅发生在链的末端,即满足我们的条件时。

  1. 用户提交表单
  2. 我们检查表格
  3. 我们向用户反馈

根据 2 的结果,我们可以返回第 1 步,也可以继续第 3 步。

模态结构:

  <div id="modal1" class="modal">
    <div class="modal-content">
      <div class="input-field">
         <input type="text" id="title"  class="validate" required="" aria-required="true">
         <label for="title">Title</label>
         <span class="helper-text" data-error="Please enter your name" data-success="Thankyou!"></span>
        </div>
    </div>
    <div class="modal-footer">
      <a id="submit-button" href="#!" class="btn">Submit</a>
      <a href="#!" class="btn modal-close waves-effect waves-red red">close</a>
    </div>
  </div>

我们根据documentation 添加可选的helper-text 范围以供用户反馈。

Javascript:

document.addEventListener('DOMContentLoaded', function() {
    
    // init modal
    var elems = document.querySelectorAll('.modal');
    var instances = M.Modal.init(elems);
  
    // get button
    var button = document.querySelector('#submit-button');
  
    // Run our own function when clicked
    button.addEventListener("click", checkForm);
  
    // Function checks for input
  
    function checkForm() {
      var input = document.querySelector('#title');
      
      if(input.value) {
        
        // submit form
        
        // add valid class to show helper
        input.classList.add('valid');
        // close modal
        instances[0].close();
        // clear form
        input.value = '';
        // remove valid class
        input.classList.remove('valid');
      } else {
        // prompt user for input
         input.classList.add('invalid');
      }
    }
  
  
  });

我们获取文本输入的值,并在此基础上添加 validinvalid 类 - 这是内置的物化内容,用于隐藏或显示我们在 data-error 中设置的相关消息和data-success.

您唯一需要添加的是实际的表单提交 - 比如form.submit()

Codepen.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    • 2019-05-29
    相关资源
    最近更新 更多