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

bxgwgixi  于 9个月前  发布在  jQuery
关注(0)|答案(7)|浏览(159)

我试图使一个登录表单中,我有电子邮件地址和密码作为文本框。我已经做了电子邮件地址的一部分,使它应该有适当的电子邮件地址,也对空检查电子邮件地址和密码文本框验证。
这是我的jsfiddle
到目前为止,我已经添加了一个警告框说,Invalid如果电子邮件地址和密码文本框是空的。而不是,我想显示一个简单的消息,就在每个文本框说,请输入您的电子邮件地址或密码,如果他们是空的?
就像在sitepoint blog上一样。
这可以在我当前的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>

字符串
我的男朋友-

<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和Servlet,所以当我点击登录按钮时,它会将我带到另一个带有有效电子邮件和密码的页面,但现在在我点击登录按钮后,没有任何事情发生。
有什么不对劲的吗?

bwitn5fc

bwitn5fc1#

你可以把静态元素放在字段后面并显示它们,或者你可以动态地注入验证消息。
此示例还遵循将焦点设置为空白字段的最佳实践,以便用户可以轻松更正问题。
请注意,您可以轻松地将其泛化到任何标签和字段(无论如何都是必填字段),而不是我的示例,它专门编码每个验证。
您的小提琴已更新,请参阅此处: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;
    }

k4aesqcs

k4aesqcs2#

我的方法是创建段落标签,在其中您希望错误消息与相同的类一起显示,并在数据无效时显示它们。

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

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

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

qhhrdooz

qhhrdooz3#

给您:
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;
}


超文本标记语言:

<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

a6b3iqyw

a6b3iqyw4#

这仅仅是找到你想要插入文本的DOM的问题。
DEMO jsfiddle

$().text();

字符串

5jvtdoz2

5jvtdoz25#

这是一个简单的解决方案,可以为您工作。
Check this solution

$('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();
});});

字符串

368yc8dk

368yc8dk6#

我们将使用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行将确保您的表单正确验证并显示所有错误消息。

rkue9o1l

rkue9o1l7#

2023回答:我采用了Dilip Kumar Choudhary的回答,并使用新的CSS规则将其删除。

CSS:

label:has(input[required]) span.LabelTxt:first-child::after {
  content: "*";
  color: red;
}
span.ErrMsgTxt{visibility:hidden;color: red;font-size:smaller;}
input:user-invalid ~ span.ErrMsgTxt{visibility:visible;}

字符串

HTML:

<form action="" method="post" onsubmit="CheckFormValidity()">
<label>
    <span class="LabelTxt">Name</span>
    <input name="name" pattern="[A-Za-z]{3,}" type="text" required>
    <span class="ErrMsgTxt">Name must be at least three characters long</span>
</label>
<br>
<label>
    <span class="LabelTxt">E-Mail</span>
    <input type="email" name="email" required>
    <span class="ErrMsgTxt">Valid e-mail required</span>
</label>
<br>
<input class="submit" type="submit" value="SUBMIT">
</form>

JavaScript:

CheckFormValidity(targetedForm=event.target){
    if (!targetedForm.checkValidity()) {
        event.preventDefault();return;
    }
}

相关问题