简体   繁体   English

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

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

I am trying to make a login form in which I have email address and password as the textbox.我正在尝试制作一个登录表单,其中我将电子邮件地址和密码作为文本框。 I have done the validation on the email address part so that it should have proper email address and also on the empty check both for email address and password text box.我已经对电子邮件地址部分进行了验证,因此它应该有正确的电子邮件地址,并且还对电子邮件地址和密码文本框进行了空检查。

Here is my jsfiddle .这是我的jsfiddle

As of now, I have added an alert box saying, Invalid if email address and password textbox is empty.截至目前,我添加了一个警告框,说如果电子邮件地址和密码文本框为空则Invalid Instead of that, I would like to show a simple message just below each text box saying , please enter your email address or password if they are empty?取而代之的是,我想在每个文本框下方显示一条简单的消息,如果它们为空,请输入您的电子邮件地址或密码?

Just like it has been done here on sitepoint blog .就像在sitepoint 博客上所做的一样。

Is this possible to do in my current HTML form?在我当前的 HTML 表单中可以这样做吗?

Update:-更新:-

<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>

And my JS -还有我的 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>

I am working with JSP and Servlets so as soon as I click Sign In button, it was taking me to another page with valid email and password earlier but now nothing is happening after I click Sign In button with valid email and password.我正在使用 JSP 和 Servlets,所以只要我单击“登录”按钮,它就会将我带到另一个带有有效电子邮件和密码的页面,但现在我单击带有有效电子邮件和密码的“登录”按钮后什么也没有发生。

Any thoughts what could be wrong?有什么想法可能是错的?

You could put static elements after the fields and show them, or you could inject the validation message dynamically.您可以在字段之后放置静态元素并显示它们,或者您可以动态注入验证消息。 See the below example for how to inject dynamically.有关如何动态注入,请参见以下示例。

This example also follows the best practice of setting focus to the blank field so user can easily correct the issue.此示例还遵循将焦点设置到空白字段的最佳实践,以便用户可以轻松纠正问题。

Note that you could easily genericize this to work with any label & field (for required fields anyway), instead of my example which specifically codes each validation.请注意,您可以轻松地将其泛化为与任何标签和字段一起使用(无论如何对于必填字段),而不是我的示例,它专门对每个验证进行编码。

Your fiddle is updated, see here: jsfiddle您的小提琴已更新,请参见此处: jsfiddle

The code:编码:

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

The CSS: CSS:

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

is only the matter of finding the dom where you want to insert the the text.只是找到要插入文本的 dom 的问题。

DEMO jsfiddle演示jsfiddle

$().text(); 

The way I would do it is to create paragraph tags where you want your error messages with the same class and show them when the data is invalid.我会这样做的方法是创建段落标记,您希望错误消息具有相同的类,并在数据无效时显示它们。 Here is my fiddle这是我的小提琴

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

I also added the paragraph tags below the email and password inputs我还在电子邮件和密码输入下方添加了段落标签

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

Here you go:干得好:

JS: 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: 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: 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>

And the fiddle: jsfiddle和小提琴: jsfiddle

This is the simple solution may work for you.这是可能对您有用的简单解决方案。

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

We will use the jQuery Validation Plugin我们将使用 jQuery 验证插件

we have to include the necessary files in our project.我们必须在我们的项目中包含必要的文件。 There are two different files to include.有两个不同的文件要包含。 The first is the core file, which includes the core features of the plugin, including everything from different validation methods to some custom selectors.第一个是核心文件,其中包含插件的核心功能,包括从不同的验证方法到一些自定义选择器的所有内容。 The second file contains additional methods to validate inputs like credit card numbers and US-based phone numbers.第二个文件包含验证信用卡号码和美国电话号码等输入的其他方法。

You can add these files to your projects via package managers like Bower or NPM.您可以通过包管理器(如 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 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 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 script Java脚本

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

This is based on the assumption that you have already added the required JavaScript files.这是基于您已经添加了所需的 JavaScript 文件的假设。 Adding those lines of JavaScript will make sure that your form is properly validated and shows all the error messages.添加这些 JavaScript 行将确保您的表单得到正确验证并显示所有错误消息。

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

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