如何使用JavaScript/jQuery进行简单的客户端表单验证?

时间:2022-12-09 10:14:55

I was doing a project series on CodeCademy and I got a project in the series to do a client side form validation using JavaScript/jQuery.

我在CodeCademy上做了一个项目系列,我在这个系列中有一个项目,用JavaScript/jQuery做客户端表单验证。

My HTML is:

我的HTML是:

<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
  <link rel='stylesheet' href='stylesheet.css' type='text/css'/>
  <script type='text/javascript' src='script.js'></script>
</head>
<body>
 <form>
  First Name : <input type='text' id='fname' placeholder='Enter First Name'><br><br>
  Last Name : <input type='text' id='lname' placeholder='Enter Last Name'><br><br>
  Age : <input type='text' id='age' placeholder='Age'><br><br>
  Sex : <input type='radio' class='sex'> Male <input type='radio' class='sex'> Female
 </form>
 <button id='submit'>Submit</button>
</body>
</html>

My JavaScript/jQuery is:

我的JavaScript / jQuery是:

$(document).ready(function()
{
 var fname = document.getElementById('fname').val();
 var lname = document.getElementById('lname').val();
 var age = document.getElementById('age').val();
 /*Do not know how to get element by class and that too, two different type. Have to check if user chose anything or not*/

  $("#submit").click(function()
  {
   if(fname.length === 0)
   {
    alert("Please input a first name");
   }
   else if(lname.length === 0)
   {
    alert("Please input a last name");
   }
   else if(age.length === 0)
   {
    alert("Please input an age");
   }
  });
});

I don't need a very complicated code and please help me in the HTML department if something is wrong there or if something needs to be added there.

我不需要非常复杂的代码,如果有什么问题或者需要添加什么东西,请在HTML部门帮助我。

Also, I don't know how to get different elements in a class. I have put a comment in my jQuery regarding that so please help if you can.

而且,我不知道如何在一个类中获得不同的元素。关于这一点,我在jQuery中做了一个评论,如果可以,请帮忙。

This is a problem in a CodeCademy project and this is where a lot of newbies in JS and jQuery have a problem, so if you can help, it'll help a lot of people and not just me.

这是CodeCademy项目中的一个问题,这是许多JS和jQuery新手遇到的问题,所以如果您能提供帮助,它将帮助很多人,而不仅仅是我。

Thanks!

谢谢!

6 个解决方案

#1


7  

You need to use .value instead of .val() since you're using pure Javascript:

您需要使用.value而不是.val(),因为您使用的是纯Javascript:

var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var age = document.getElementById('age').value;

if you want to use .val() method then you need a jQuery object:

如果要使用.val()方法,则需要一个jQuery对象:

var fname = $('#fname').val();
var lname = $('#lname').val();
var age = $('#age').val();

You also need to put those variables inside .click() handler in order to get the updated value of these textboxes, currently you only retrieve the value on page load which is always equal to 0:

您还需要将这些变量放入.click()处理程序,以获得这些文本框的更新值,当前您只需要在页面加载中检索值,该值始终为0:

$(document).ready(function () {
    $("#submit").click(function () {
        var fname = document.getElementById('fname').value;
        var lname = document.getElementById('lname').value;
        var age = document.getElementById('age').value;

        if (fname.length == 0) {
            alert("Please input a first name");
        } else if (lname.length == 0) {
            alert("Please input a last name");
        } else if (age.length == 0) {
            alert("Please input an age");
        }
    });
});

Fiddle Demo

小提琴演示

#2


1  

Check it out this simple plugin

看看这个简单的插件

http://suraj-mahajan.github.io/Validate-In-Grid-Controls/

http://suraj-mahajan.github.io/Validate-In-Grid-Controls/

#3


0  

from your example, get elements by class name

从示例中,按类名获取元素

var lists = document.getElementsByClassName("sex");

to access specific value use lists[0].value it will return "Male" or lists[1].value will return "Female"

要访问特定的值,请使用清单[0]。值它将返回“Male”或列出[1]。值将返回“女性”

if you use native/pure javascript use .value not val() . val() is only for jquery

如果使用本机/纯javascript,则使用.value而不是val()。val()仅适用于jquery

#4


0  

It looks like you're asking a couple questions at once.

看起来你同时问了几个问题。

As suzonraj, pointed out you need document.getElementsByClass to get elements by class name and as Felix pointed out, you need to place your data look up inside your .click event in order to get the current, not page .ready value.

正如suzonraj所说,你需要文件。getElementsByClass根据类名获取元素,正如Felix指出的,您需要将数据查找放在.click事件中,以便获得当前的而不是page .ready值。

I will add that you should add the name parameter to your radio boxes, so they actually function like radio boxes - turning one off when another is clicked. With this, you could use document.getElementsByName, which is really what you're after with a radio collection.

我要补充的是,你应该把name参数添加到你的单选框中,这样它们的功能就像单选框一样——当你点击另一个单选框时,它就会自动关闭。这样,您就可以使用文档了。getElementsByName,这就是你想要的无线电收藏。

As far as validation, you would then need to go through your array of elements by name or class, and then validate that at least one is .checked.

至于验证,则需要按名称或类遍历元素数组,然后验证至少一个元素是.checked。

Here is an example based off the code Felix shared: http://jsfiddle.net/5zqW7/8/

下面是一个基于Felix共享的代码的示例:http://jsfiddle.net/5zqW7/8/

One addition, is that validation occurs for all elements rather than just until the first element that fails. This is a little more communicative to the user, as it will identify all the wrong fields, not just the first, hit submit, then the second, and so on. In a real form, you'd probably have something less loud than an alert() anyhow. That may not be necessary for your assignment.

另外,验证发生在所有元素上,而不是在第一个元素失败之前。这对用户来说更具交流性,因为它将识别所有错误的字段,而不仅仅是第一个字段、点击submit、然后是second等等。在一个真实的形式中,你可能会比一个警告()的声音小一些。这可能对你的作业没有必要。

#5


0  

Here is very simple way to make form validation using jquery

使用jquery进行表单验证的方法非常简单

// Wait for the DOM to be ready
$(function() {
  // Initialize form validation on the registration form.
  // It has the name attribute "registration"
  $("form[name='registration']").validate({
    // Specify validation rules
    rules: {
      // The key name on the left side is the name attribute
      // of an input field. Validation rules are defined
      // on the right side
      firstname: "required",
      lastname: "required",
      email: {
        required: true,
        // Specify that email should be validated
        // by the built-in "email" rule
        email: true
      },
      password: {
        required: true,
        minlength: 5
      }
    },
    // Specify validation error messages
    messages: {
      firstname: "Please enter your firstname",
      lastname: "Please enter your lastname",

      password: {
        required: "Please provide a password",
        minlength: "Your password must be at least 5 characters long"
      },
      email: {
        required: "Please provide a valid user name",
        email: "Please enter a valid email address"
      }
    },
    // Make sure the form is submitted to the destination defined
    // in the "action" attribute of the form when valid
    submitHandler: function(form) {
      form.submit();
    }
  });
});
@import url("https://fonts.googleapis.com/css?family=Open+Sans");

/* Styles */

* {
  margin: 0;
  padding: 0;
}

body {
  font-family: "Open Sans";
  font-size: 14px;
}

.container {
  width: 500px;
  margin: 25px auto;
}

form {
  padding: 20px;
  background: #2c3e50;
  color: #fff;
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;
  border-radius: 4px;
}

form label,
form input,
form button {
  border: 0;
  margin-bottom: 3px;
  display: block;
  width: 100%;
}

form input {
  height: 25px;
  line-height: 25px;
  background: #fff;
  color: #000;
  padding: 0 6px;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

form button {
  height: 30px;
  line-height: 30px;
  background: #e67e22;
  color: #fff;
  margin-top: 10px;
  cursor: pointer;
}

label.error {
  color: #ff0000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src='https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js'></script>
<div class="container">
  <h2>Registration</h2>
  <form action="" name="registration">
    <label for="email">Email</label>
    <input type="email" name="email" id="email" placeholder="john@doe.com" />
    <label for="password">Password</label>
    <input type="password" name="password" id="password" placeholder="&#9679;&#9679;&#9679;&#9679;&#9679;" />
    <button type="submit">Register</button>
  </form>
</div>

#6


0  

function validate() {
    var scheduledOn = $("#ScheduledOn").val();
    var status = $(".Status option:selected").text();
    var result = true;

    if (id == "") {
        var scheduledOn = $("#ScheduledOn").val();
        var category = $(".categoryList option:selected").text();
        var activityTask = $(".activityTaskList option:selected").text();

        var lead = $("#LeadID").val();
        var agent = $("#AgentID").val();

        if (category == "Select Category") {
            $("#categoryValidation").show();
            $("#categoryValidation").text("The Category field is required");
        }
        else {
            $("#categoryValidation").hide();
        }

        if (category == "Agent Recruitment" || category == "Direct Sales" || category == "Joint Field Work" || category == "Select Category" || category == "Agent Development") {
            var activityTask = $(".activityTaskList option:selected").text();

            if (activityTask == "Select Activity Task") {
                $("#activityTaskValidation").show();
                $("#activityTaskValidation").text("The Activity Task field is required");
            }
            else {
                $("#activityTaskValidation").hide();
            }
        }

        if (category == "Joint Field Work") {
            if (agent == "" || agent == "Select Agent") {
                $("#agentValidation").show();
                $("#agentValidation").text("The Agent field is required");
                result = false;
            }
            else {
                $("#agentValidation").hide();
            }
        }

        if (category == "Joint Field Work") {
            if (lead == "" || lead == null || lead == "Select Lead") {
                $("#leadValidation").show();
                $("#leadValidation").text("The Lead field is required");
                result = false;
            }

            else {
                $("#leadValidation").hide();
            }
        }

        if (category == "Agent Recruitment" || category == "Agent Development") {
            if (agent == "" || agent == "Select Agent") {
                $("#agentValidation").show();
                $("#agentValidation").text("The Agent field is required");
                result = false;
            }
            else {
                $("#agentValidation").hide();
            }
        }

        if (category == "Direct Sales") {
            if (lead == "" || lead == "Select Lead" || lead == null) {
                $("#leadValidation").show();
                $("#leadValidation").text("The Lead field is required");
                result = false;
            }
            else {
                $("#leadValidation").hide();
            }
        }

        if (scheduledOn == "" || scheduledOn == null) {
            $("#scheduledOnValidation").show();
            $("#scheduledOnValidation").text("The Scheduled On field is required");
            result = false;
        }
        else if (Date.parse(scheduledOn) <= Date.now()) {
            $("#scheduledOnValidation").show();
            $("#scheduledOnValidation").text("The Scheduled On field should be greater than current date time");
            result = false;
        }
        else {
            $("#scheduledOnValidation").hide();
        }

        return result;
    }
    else {
        var scheduledOn = $("#NewScheduledOn").val();
        var status = $(".Status option:selected").text();

        if (document.getElementById("SetAppointment_Y").checked) {
            var activityTask = $(".activityTaskList").val();

            if (activityTask == null || activityTask == "") {
                $("#activityTaskValidation").show();
                $("#activityTaskValidation").text("The Activity Task field is required");
                result = false;
            }
            else {
                $("#activityTaskValidation").hide();
                $("#scheduledOnValidation").hide();
            }

            if (status != null && (scheduledOn == "" || scheduledOn == null)) {
                $("#scheduledOnValidation").show();
                $("#scheduledOnValidation").text("The Scheduled On field is required");
                $("#statusValidation").hide();
                result = false;
            }
            else if (Date.parse(scheduledOn) <= Date.now()) {
                $("#scheduledOnValidation").show();
                $("#scheduledOnValidation").text("The Scheduled On field should be greater than current date time");
                result = false;
            }
            else {
                $("#scheduledOnValidation").hide();
                $("#statusValidation").show();
            }
        }
    }

    return result;
}

#1


7  

You need to use .value instead of .val() since you're using pure Javascript:

您需要使用.value而不是.val(),因为您使用的是纯Javascript:

var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var age = document.getElementById('age').value;

if you want to use .val() method then you need a jQuery object:

如果要使用.val()方法,则需要一个jQuery对象:

var fname = $('#fname').val();
var lname = $('#lname').val();
var age = $('#age').val();

You also need to put those variables inside .click() handler in order to get the updated value of these textboxes, currently you only retrieve the value on page load which is always equal to 0:

您还需要将这些变量放入.click()处理程序,以获得这些文本框的更新值,当前您只需要在页面加载中检索值,该值始终为0:

$(document).ready(function () {
    $("#submit").click(function () {
        var fname = document.getElementById('fname').value;
        var lname = document.getElementById('lname').value;
        var age = document.getElementById('age').value;

        if (fname.length == 0) {
            alert("Please input a first name");
        } else if (lname.length == 0) {
            alert("Please input a last name");
        } else if (age.length == 0) {
            alert("Please input an age");
        }
    });
});

Fiddle Demo

小提琴演示

#2


1  

Check it out this simple plugin

看看这个简单的插件

http://suraj-mahajan.github.io/Validate-In-Grid-Controls/

http://suraj-mahajan.github.io/Validate-In-Grid-Controls/

#3


0  

from your example, get elements by class name

从示例中,按类名获取元素

var lists = document.getElementsByClassName("sex");

to access specific value use lists[0].value it will return "Male" or lists[1].value will return "Female"

要访问特定的值,请使用清单[0]。值它将返回“Male”或列出[1]。值将返回“女性”

if you use native/pure javascript use .value not val() . val() is only for jquery

如果使用本机/纯javascript,则使用.value而不是val()。val()仅适用于jquery

#4


0  

It looks like you're asking a couple questions at once.

看起来你同时问了几个问题。

As suzonraj, pointed out you need document.getElementsByClass to get elements by class name and as Felix pointed out, you need to place your data look up inside your .click event in order to get the current, not page .ready value.

正如suzonraj所说,你需要文件。getElementsByClass根据类名获取元素,正如Felix指出的,您需要将数据查找放在.click事件中,以便获得当前的而不是page .ready值。

I will add that you should add the name parameter to your radio boxes, so they actually function like radio boxes - turning one off when another is clicked. With this, you could use document.getElementsByName, which is really what you're after with a radio collection.

我要补充的是,你应该把name参数添加到你的单选框中,这样它们的功能就像单选框一样——当你点击另一个单选框时,它就会自动关闭。这样,您就可以使用文档了。getElementsByName,这就是你想要的无线电收藏。

As far as validation, you would then need to go through your array of elements by name or class, and then validate that at least one is .checked.

至于验证,则需要按名称或类遍历元素数组,然后验证至少一个元素是.checked。

Here is an example based off the code Felix shared: http://jsfiddle.net/5zqW7/8/

下面是一个基于Felix共享的代码的示例:http://jsfiddle.net/5zqW7/8/

One addition, is that validation occurs for all elements rather than just until the first element that fails. This is a little more communicative to the user, as it will identify all the wrong fields, not just the first, hit submit, then the second, and so on. In a real form, you'd probably have something less loud than an alert() anyhow. That may not be necessary for your assignment.

另外,验证发生在所有元素上,而不是在第一个元素失败之前。这对用户来说更具交流性,因为它将识别所有错误的字段,而不仅仅是第一个字段、点击submit、然后是second等等。在一个真实的形式中,你可能会比一个警告()的声音小一些。这可能对你的作业没有必要。

#5


0  

Here is very simple way to make form validation using jquery

使用jquery进行表单验证的方法非常简单

// Wait for the DOM to be ready
$(function() {
  // Initialize form validation on the registration form.
  // It has the name attribute "registration"
  $("form[name='registration']").validate({
    // Specify validation rules
    rules: {
      // The key name on the left side is the name attribute
      // of an input field. Validation rules are defined
      // on the right side
      firstname: "required",
      lastname: "required",
      email: {
        required: true,
        // Specify that email should be validated
        // by the built-in "email" rule
        email: true
      },
      password: {
        required: true,
        minlength: 5
      }
    },
    // Specify validation error messages
    messages: {
      firstname: "Please enter your firstname",
      lastname: "Please enter your lastname",

      password: {
        required: "Please provide a password",
        minlength: "Your password must be at least 5 characters long"
      },
      email: {
        required: "Please provide a valid user name",
        email: "Please enter a valid email address"
      }
    },
    // Make sure the form is submitted to the destination defined
    // in the "action" attribute of the form when valid
    submitHandler: function(form) {
      form.submit();
    }
  });
});
@import url("https://fonts.googleapis.com/css?family=Open+Sans");

/* Styles */

* {
  margin: 0;
  padding: 0;
}

body {
  font-family: "Open Sans";
  font-size: 14px;
}

.container {
  width: 500px;
  margin: 25px auto;
}

form {
  padding: 20px;
  background: #2c3e50;
  color: #fff;
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;
  border-radius: 4px;
}

form label,
form input,
form button {
  border: 0;
  margin-bottom: 3px;
  display: block;
  width: 100%;
}

form input {
  height: 25px;
  line-height: 25px;
  background: #fff;
  color: #000;
  padding: 0 6px;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

form button {
  height: 30px;
  line-height: 30px;
  background: #e67e22;
  color: #fff;
  margin-top: 10px;
  cursor: pointer;
}

label.error {
  color: #ff0000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src='https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js'></script>
<div class="container">
  <h2>Registration</h2>
  <form action="" name="registration">
    <label for="email">Email</label>
    <input type="email" name="email" id="email" placeholder="john@doe.com" />
    <label for="password">Password</label>
    <input type="password" name="password" id="password" placeholder="&#9679;&#9679;&#9679;&#9679;&#9679;" />
    <button type="submit">Register</button>
  </form>
</div>

#6


0  

function validate() {
    var scheduledOn = $("#ScheduledOn").val();
    var status = $(".Status option:selected").text();
    var result = true;

    if (id == "") {
        var scheduledOn = $("#ScheduledOn").val();
        var category = $(".categoryList option:selected").text();
        var activityTask = $(".activityTaskList option:selected").text();

        var lead = $("#LeadID").val();
        var agent = $("#AgentID").val();

        if (category == "Select Category") {
            $("#categoryValidation").show();
            $("#categoryValidation").text("The Category field is required");
        }
        else {
            $("#categoryValidation").hide();
        }

        if (category == "Agent Recruitment" || category == "Direct Sales" || category == "Joint Field Work" || category == "Select Category" || category == "Agent Development") {
            var activityTask = $(".activityTaskList option:selected").text();

            if (activityTask == "Select Activity Task") {
                $("#activityTaskValidation").show();
                $("#activityTaskValidation").text("The Activity Task field is required");
            }
            else {
                $("#activityTaskValidation").hide();
            }
        }

        if (category == "Joint Field Work") {
            if (agent == "" || agent == "Select Agent") {
                $("#agentValidation").show();
                $("#agentValidation").text("The Agent field is required");
                result = false;
            }
            else {
                $("#agentValidation").hide();
            }
        }

        if (category == "Joint Field Work") {
            if (lead == "" || lead == null || lead == "Select Lead") {
                $("#leadValidation").show();
                $("#leadValidation").text("The Lead field is required");
                result = false;
            }

            else {
                $("#leadValidation").hide();
            }
        }

        if (category == "Agent Recruitment" || category == "Agent Development") {
            if (agent == "" || agent == "Select Agent") {
                $("#agentValidation").show();
                $("#agentValidation").text("The Agent field is required");
                result = false;
            }
            else {
                $("#agentValidation").hide();
            }
        }

        if (category == "Direct Sales") {
            if (lead == "" || lead == "Select Lead" || lead == null) {
                $("#leadValidation").show();
                $("#leadValidation").text("The Lead field is required");
                result = false;
            }
            else {
                $("#leadValidation").hide();
            }
        }

        if (scheduledOn == "" || scheduledOn == null) {
            $("#scheduledOnValidation").show();
            $("#scheduledOnValidation").text("The Scheduled On field is required");
            result = false;
        }
        else if (Date.parse(scheduledOn) <= Date.now()) {
            $("#scheduledOnValidation").show();
            $("#scheduledOnValidation").text("The Scheduled On field should be greater than current date time");
            result = false;
        }
        else {
            $("#scheduledOnValidation").hide();
        }

        return result;
    }
    else {
        var scheduledOn = $("#NewScheduledOn").val();
        var status = $(".Status option:selected").text();

        if (document.getElementById("SetAppointment_Y").checked) {
            var activityTask = $(".activityTaskList").val();

            if (activityTask == null || activityTask == "") {
                $("#activityTaskValidation").show();
                $("#activityTaskValidation").text("The Activity Task field is required");
                result = false;
            }
            else {
                $("#activityTaskValidation").hide();
                $("#scheduledOnValidation").hide();
            }

            if (status != null && (scheduledOn == "" || scheduledOn == null)) {
                $("#scheduledOnValidation").show();
                $("#scheduledOnValidation").text("The Scheduled On field is required");
                $("#statusValidation").hide();
                result = false;
            }
            else if (Date.parse(scheduledOn) <= Date.now()) {
                $("#scheduledOnValidation").show();
                $("#scheduledOnValidation").text("The Scheduled On field should be greater than current date time");
                result = false;
            }
            else {
                $("#scheduledOnValidation").hide();
                $("#statusValidation").show();
            }
        }
    }

    return result;
}