错误消息未呈现|网址验证

时间:2021-02-06 03:23:51

标签: javascript html

我正在尝试在提交非 url 时在 HTML 表单中呈现错误消息,因为我需要能够轻松调整位置并应用 CSS 样式。

我之所以要经历这个,而不只是简单地使用 type=url,因为我不喜欢标准的 chrome 验证错误消息,我想把我自己的消息放在表单下面。

目前,提交非 url 时没有显示错误消息,并且我的控制台中没有错误。有什么想法吗?

HTML

<form method="POST" id="Submit">
    <div class="inner-form">
        <div class="input-field first-wrap">
            <div class="svg-wrapper">
                <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="24"
                    height="24"
                    viewBox="0 0 24 24"
                >
                    <path
                        d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z "
                    ></path>
                </svg>
            </div>
            <input
                id="search"
                name="url"
                placeholder="Paste a domain here"
                type="url"
                required
                oninvalid="onInvalid(event)"
            />
        </div>

        <div class="input-field second-wrap">
            <button
                id="button"
                class="btn-search"
                onclick="searchIt()"
                value="press"
                type="submit"
            >
                SEARCH
            </button>
        </div>
    </div>
    <p class="errorMessage" id="errorMessage">Yikes! That's not a valid URL.</p>
</form>

JS

function onInvalid(ev) {
   ev.preventDefault();
   document.getElementById('errorMessage').innerText = "Yikes! That's not a valid URL";
}

CSS

#errorMessage {
   display: none;
   color: #EB7051;
   font-size: 15px;
}

可能是因为 display: none 吗?我只希望它在无效网址(不包含 http:// 或 https://)时显示,然后在提交有效网址时消失

所需结果的编辑:

enter image description here

1 个答案:

答案 0 :(得分:1)

根据我的评论,我能够设置一个示例,该示例允许显示在受影响的输入之后放置的特定标签。如果您想修改标签中的消息,您可能希望使用已有的 javascript 将其绑定 请参阅下文。

  <!DOCTYPE html>
<html>
<head>
<style>
.errorMessage {
   display: none;
   color: #EB7051;
   font-size: 15px;
}

input:focus:invalid + p {
    display:block;
}
</style>
</head>
<body>
    <form method="POST" id="Submit" >
        <div class="inner-form">
             <div class="input-field first-wrap">                    
                  <input id="search" name="url" placeholder="Paste a domain here" type="url" required />
                  <p class="errorMessage">Yikes! That's not a valid URL.</p>
             </div>
             <div class="input-field second-wrap">
                 <button id="button" class="btn-search" value="press" type="submit">SEARCH</button>
             </div>
        </div>
    </form>
</body>
</html>

以上示例基于此处的想法https://www.digitalocean.com/community/tutorials/css-styling-form-input-validity