繁体   English   中英

如何使用 jQuery 在每个文本框下方显示验证消息?

[英]How to show validation message below each textbox using jQuery?

我正在尝试制作一个登录表单,其中我将电子邮件地址和密码作为文本框。 我已经对电子邮件地址部分进行了验证,因此它应该有正确的电子邮件地址,并且还对电子邮件地址和密码文本框进行了空检查。

这是我的jsfiddle

截至目前,我添加了一个警告框,说如果电子邮件地址和密码文本框为空则Invalid 取而代之的是,我想在每个文本框下方显示一条简单的消息,如果它们为空,请输入您的电子邮件地址或密码?

就像在sitepoint 博客上所做的一样。

在我当前的 HTML 表单中可以这样做吗?

更新:-

<body>

    <div id="login">

        <h2>
            <span class="fontawesome-lock"></span>Sign In
        </h2>

        <form action="login" method="POST">
            <fieldset>
                <p>
                    <label for="email">E-mail address</label>
                </p>
                <p>
                    <input type="email" id="email" name="email">
                </p>
                <p>
                    <label for="password">Password</label>
                </p>
                <p>
                    <input type="password" name="password" id="password">
                </p>
                <p>
                    <input type="submit" value="Sign In">
                </p>

            </fieldset>

        </form>

    </div>
    <!-- end login -->

</body>

还有我的 JS -

<script>
    $(document).ready(function() {
        $('form').on('submit', function (e) {
            e.preventDefault();

            if (!$('#email').val()) {
                if ($("#email").parent().next(".validation").length == 0) // only add if not added
                {
                    $("#email").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter email address</div>");
                }
            } else {
                $("#email").parent().next(".validation").remove(); // remove it
            }
            if (!$('#password').val()) {
                if ($("#password").parent().next(".validation").length == 0) // only add if not added
                {
                    $("#password").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter password</div>");

                }
            } else {
                $("#password").parent().next(".validation").remove(); // remove it
            }
        }); 
    });

</script>

我正在使用 JSP 和 Servlets,所以只要我单击“登录”按钮,它就会将我带到另一个带有有效电子邮件和密码的页面,但现在我单击带有有效电子邮件和密码的“登录”按钮后什么也没有发生。

有什么想法可能是错的?

您可以在字段之后放置静态元素并显示它们,或者您可以动态注入验证消息。 有关如何动态注入,请参见以下示例。

此示例还遵循将焦点设置到空白字段的最佳实践,以便用户可以轻松纠正问题。

请注意,您可以轻松地将其泛化为与任何标签和字段一起使用(无论如何对于必填字段),而不是我的示例,它专门对每个验证进行编码。

您的小提琴已更新,请参见此处: jsfiddle

编码:

$('form').on('submit', function (e) {
    var focusSet = false;
    if (!$('#email').val()) {
        if ($("#email").parent().next(".validation").length == 0) // only add if not added
        {
            $("#email").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter email address</div>");
        }
        e.preventDefault(); // prevent form from POST to server
        $('#email').focus();
        focusSet = true;
    } else {
        $("#email").parent().next(".validation").remove(); // remove it
    }
    if (!$('#password').val()) {
        if ($("#password").parent().next(".validation").length == 0) // only add if not added
        {
            $("#password").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter password</div>");
        }
        e.preventDefault(); // prevent form from POST to server
        if (!focusSet) {
            $("#password").focus();
        }
    } else {
        $("#password").parent().next(".validation").remove(); // remove it
    }
});  

CSS:

    .validation
    {
      color: red;
      margin-bottom: 20px;
    }

只是找到要插入文本的 dom 的问题。

演示jsfiddle

$().text(); 

我会这样做的方法是创建段落标记,您希望错误消息具有相同的类,并在数据无效时显示它们。 这是我的小提琴

if ($('#email').val() == '' || !$('#password').val() == '') {
    $('.loginError').show();
    return false;
}

我还在电子邮件和密码输入下方添加了段落标签

<p class="loginError" style="display:none;">please enter your email address or password.</p>

干得好:

JS:

$('form').on('submit', function (e) {
    e.preventDefault();
    
    if (!$('#email').val()) 
        $('#email').parent().append('<span class="error">Please enter your email address.</span>');
    
    
    if(!$('#password').val())
         $('#password').parent().append('<span class="error">Please enter your password.</span>');
});

CSS:

@charset "utf-8";
/* CSS Document */

/* ---------- FONTAWESOME ---------- */
/* ---------- http://fortawesome.github.com/Font-Awesome/ ---------- */
/* ---------- http://weloveiconfonts.com/ ---------- */

@import url(http://weloveiconfonts.com/api/?family=fontawesome);

/* ---------- ERIC MEYER'S RESET CSS ---------- */
/* ---------- http://meyerweb.com/eric/tools/css/reset/ ---------- */

@import url(http://meyerweb.com/eric/tools/css/reset/reset.css);

/* ---------- FONTAWESOME ---------- */

[class*="fontawesome-"]:before {
  font-family: 'FontAwesome', sans-serif;
}

/* ---------- GENERAL ---------- */

body {
    background-color: #C0C0C0;
    color: #000;
    font-family: "Varela Round", Arial, Helvetica, sans-serif;
    font-size: 16px;
    line-height: 1.5em;
}

input {
    border: none;
    font-family: inherit;
    font-size: inherit;
    font-weight: inherit;
    line-height: inherit;
    -webkit-appearance: none;
}

/* ---------- LOGIN ---------- */

#login {
    margin: 50px auto;
    width: 400px;
}

#login h2 {
    background-color: #f95252;
    -webkit-border-radius: 20px 20px 0 0;
    -moz-border-radius: 20px 20px 0 0;
    border-radius: 20px 20px 0 0;
    color: #fff;
    font-size: 28px;
    padding: 20px 26px;
}

#login h2 span[class*="fontawesome-"] {
    margin-right: 14px;
}

#login fieldset {
    background-color: #fff;
    -webkit-border-radius: 0 0 20px 20px;
    -moz-border-radius: 0 0 20px 20px;
    border-radius: 0 0 20px 20px;
    padding: 20px 26px;
}

#login fieldset div {
    color: #777;
    margin-bottom: 14px;
}

#login fieldset p:last-child {
    margin-bottom: 0;
}

#login fieldset input {
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;
}

#login fieldset .error {
    display: block;
     color: #FF1000;
    font-size: 12px;
}
}

#login fieldset input[type="email"], #login fieldset input[type="password"] {
    background-color: #eee;
    color: #777;
    padding: 4px 10px;
    width: 328px;
}

#login fieldset input[type="submit"] {
    background-color: #33cc77;
    color: #fff;
    display: block;
    margin: 0 auto;
    padding: 4px 0;
    width: 100px;
}

#login fieldset input[type="submit"]:hover {
    background-color: #28ad63;
}

HTML:

<div id="login">

<h2><span class="fontawesome-lock"></span>Sign In</h2>

<form action="javascript:void(0);" method="POST">

    <fieldset>

        <div><label for="email">E-mail address</label></div>
        <div><input type="email" id="email" /></div>

        <div><label for="password">Password</label></div>
        <div><input type="password" id="password" /></div> <!-- JS because of IE support; better: placeholder="Email" -->

        <div><input type="submit" value="Sign In"></div>

    </fieldset>

</form>

和小提琴: jsfiddle

这是可能对您有用的简单解决方案。

检查此解决方案

$('form').on('submit', function (e) {
e.preventDefault();
var emailBox=$("#email");
var passBox=$("#password");
if (!emailBox.val() || !passBox.val()) {
    $(".validationText").text("Please Enter Value").show();
}
else if(!IsEmail(emailBox.val()))
{
    emailBox.prev().text("Invalid E-mail").show();
}
$("input#email, input#password").focus(function(){
    $(this).prev(".validationText").hide();
});});

我们将使用 jQuery 验证插件

我们必须在我们的项目中包含必要的文件。 有两个不同的文件要包含。 第一个是核心文件,其中包含插件的核心功能,包括从不同的验证方法到一些自定义选择器的所有内容。 第二个文件包含验证信用卡号码和美国电话号码等输入的其他方法。

您可以通过包管理器(如 Bower 或 NPM)将这些文件添加到您的项目中。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>

HTML

   <form id="basic-form" action="" method="post">
    <p>
      <label for="name">Name <span>(required, at least 3 characters)</span></label>
      <input id="name" name="name" minlength="3" type="text" required>
    </p>
    <p>
      <label for="email">E-Mail <span>(required)</span></label>
      <input id="email" type="email" name="email" required>
    </p>
    <p>
      <input class="submit" type="submit" value="SUBMIT">
    </p>
</form>

CSS

   body {
  margin: 20px 0;
  font-family: 'Lato';
  font-weight: 300;
  font-size: 1.25rem;
  width: 300px;
}

form, p {
  margin: 20px;
}

p.note {
  font-size: 1rem;
  color: red;
}

input {
  border-radius: 5px;
  border: 1px solid #ccc;
  padding: 4px;
  font-family: 'Lato';
  width: 300px;
  margin-top: 10px;
}

label {
  width: 300px;
  font-weight: bold;
  display: inline-block;
  margin-top: 20px;
}

label span {
  font-size: 1rem;
}

label.error {
    color: red;
    font-size: 1rem;
    display: block;
    margin-top: 5px;
}

input.error {
    border: 1px dashed red;
    font-weight: 300;
    color: red;
}

[type="submit"], [type="reset"], button, html [type="button"] {
    margin-left: 0;
    border-radius: 0;
    background: black;
    color: white;
    border: none;
    font-weight: 300;
    padding: 10px 0;
    line-height: 1;
}

Java脚本

 $(document).ready(function() {
  $("#basic-form").validate();
});

这是基于您已经添加了所需的 JavaScript 文件的假设。 添加这些 JavaScript 行将确保您的表单得到正确验证并显示所有错误消息。

暂无
暂无

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

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