簡體   English   中英

帶有 Vanilla JS 故障的 Bootstrap 4 表單驗證

[英]Bootstrap 4 form validation with Vanilla JS malfunction

我能夠創建一個腳本來驗證我的 Bootstrap 4 表單,但不知何故錯誤消息正在替換輸入字段。 是否有一種優雅的方法可以使用 Vanilla JS 驗證 BS4,或者我應該在使用 Bootstrap 驗證的道路上只使用 go? 業界最佳實踐是什么? 這是我第一次處理表單驗證。

這是小提琴:

https://jsfiddle.net/wunrsjdy/

HTML:

          <div class="container">
            <div id="form">
              <h1 class="page-title">Quer Ser Nosso Cliente? Preencha o Questionário Abaixo</h1>



              <form id="form-user" action ="#" method="POST">
                <div class="form-group" id='errorTeste'>
                  <label for="name">Empresa</label>
                  <input type="text" class="form-control" id="name" name= "name" placeholder="">
                </div>

                <button type="submit" class="btn btn-primary" id="button-send">Enviar</button>
                </form>


            </div>


JS

const name = document.getElementById('name')
const form = document.getElementById('form-user')
const errorElement = document.getElementById('errorTeste')

form.addEventListener('submit', (e) => {
    let messages = []
    if (name.value === '' || name.value == null) {
        messages.push('Preencha o nome')
    }

    if (messages.length > 0) {

    e.preventDefault()
    errorElement.innerText = messages.join(', ')
    }
})

在您的小提琴中,您正在更改errorElementinnerText屬性。 但是errorElement也是(等於)您的.form-group元素:

const errorElement = document.getElementById('errorTeste')

// A little further down your html...
<div class="form-group" id='errorTeste'>

我相信這會導致您的input.form-group中的label元素被內部文本替換。

不過,我覺得你走在正確的軌道上。 嘗試使用元素的style.display屬性在用戶輸入無效時顯示另一個包含樣式錯誤/警告消息的元素。 也許您嘗試將#errorTeste id 分配給單獨的錯誤消息元素,但不小心將其分配給了.form-group元素? 只是一種預感。

這是一個不錯的示例,說明如何使它看起來:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM