欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

用Javascript和PHP进行表单验证

程序员文章站 2022-03-08 18:53:28
...
用Javascript和PHP进行表单验证
用Javascript和PHP进行表单验证

Form Validation with Javascript and PHP In this tutorial, we will show you how to create an attractive, pleasant to look form for your website, and then we will explain how to dynamically validate it using Javascript. The server-side validation with PHP will be covered too (to make everything 100% safe). This tutorial will help you to add more functionality to your forms that leads to better user experience and better website quality. You may also enhance your already existing forms with adding some fancy effects that are presented in this tutorial. Let us get started! Info: If you’d like to modify your existing forms, skip the HTML and CSS sections of this tutorial and go ahead to step number five. Otherwise, if you’re planning to create a new form, start reading since the beginning.

使用Javascript和PHP进行表单验证在本教程中,我们将向您展示如何为您的网站创建美观,美观的表单,然后说明如何使用Javascript动态验证表单。 还将涵盖使用PHP进行服务器端验证的过程(以使所有内容100%安全)。 本教程将帮助您向表单中添加更多功能,从而带来更好的用户体验和更好的网站质量。 您还可以通过添加一些本教程中介绍的精美效果来增强您现有的表单。 让我们开始吧! 信息:如果要修改现有表单,请跳过本教程HTML和CSS部分,然后继续执行第五步。 否则,如果您打算创建新表格,请从头开始阅读。

概念 (Concept)

Let’s start with some brief explanation of what are we going to do. I’m sure that you have already seen a lots of different forms and you already noted that filling in some of them was much more convinient than filling in other ones. By and large, good ones were enhanced with additional scripts. We are going to cover several field types including standard input field, password field, repeat password field, email field, options list and few different js scripts. We hope that you’ll find here something useful for you. There are several things to consider before you creating forms:

让我们从一些简短的解释开始。 我敢肯定,您已经看到了许多不同的表格,并且您已经注意到,填写其中的某些表格比填写其他表格更为方便。 总的来说,好的脚本通过附加脚本得到了增强。 我们将介绍几种字段类型,包括标准输入字段,密码字段,重复密码字段,电子邮件字段,选项列表和一些不同的js脚本。 我们希望您会在这里找到对您有用的东西。 创建表单之前,需要考虑以下几件事:

  • Make sure that your form is as short as possible. People don’t like wasting time on filling in complex (and long) forms. They are likely to leave the page before they take any action. It’s better to require for less important information after user is already joined (preferably, only when you really need that information).

    确保您的表格越短越好。 人们不喜欢浪费时间填写复杂(且冗长)的表格。 他们可能会在采取任何措施之前离开页面。 最好在用户加入后要求较少的重要信息(最好仅在您确实需要该信息时)。
  • We want it to look neat and clean.

    我们希望它看起来干净整洁。
  • We want it to work seamlessly and without any strange behavior or errors.

    我们希望它无缝运行,并且没有任何奇怪的行为或错误。
  • We want to reduce number of fake submissions.

    我们希望减少虚假提交的数量。
现场演示

[sociallocker]

[社交储物柜]

打包下载

[/sociallocker]

[/ sociallocker]

项目 (Project)

We’re going to start with HTML and then improve it with styles and scripts. At the end we’re going to use the following fields in my form (numbers of allowed chars are in the brackets):

我们将从HTML开始,然后通过样式和脚本对其进行改进。 最后,我们将在表单中使用以下字段(括号中允许使用的字符数):

  • Name (25)

    名字(25)
  • Password (25)

    密码(25)
  • Password Confirmation (25)

    密码确认(25)
  • Email (50)

    电邮(50)
  • Gender (boolean)

    性别(布尔值)

This is the plan: the best way to make each part is to start with HTML and then improve it by adding some style and scripts but you can actually start with preparing database (because you may have your own DB structure) or PHP script (step 12) and then, take care of the other steps. Tip: You always can increase maximum size of your text fields (it you need).

这是计划:制作每个部分的最佳方法是从HTML开始,然后通过添加一些样式和脚本对其进行改进,但实际上可以从准备数据库(因为您可能具有自己的数据库结构)或PHP脚本(步骤)开始。 12),然后执行其他步骤。 提示:您总是可以增加文本字段的最大大小(需要时)。

第1步-HTML表单 (Step 1 – HTML Forms)

Let’s prepare a new folder ‘templates’, where we will put all our html templates. Create a new document and name it ‘main_page.html’. Now we’re going to create a new HTML form and put it here. As you can see below, there are some comments referring to each part of my code, so I believe that at this point additional explanations are superfluous. I have also created a HTML table to align all the information. Here is the code:

让我们准备一个新的文件夹“ templates”,在其中放置所有的html模板。 创建一个新文档并将其命名为“ main_page.html”。 现在,我们将创建一个新HTML表单并将其放在此处。 如您在下面看到的,有一些注释指向我的代码的每个部分,因此,我相信在这一点上多余的解释是多余的。 我还创建了一个HTML表来对齐所有信息。 这是代码:

templates / main_page.html (templates/main_page.html)


<form action="index.php" method="post" id="form" onsubmit="return validate_all('results');">
    <table cellspacing="10">
        <tr><td>Login</td><td><input type="text" name="login" maxlength="25" id="login" onKeyUp="updatelength('login', 'login_length')"><br /><div id="login_length"></div> </td></tr>
        <tr><td>Password</td><td><input type="password" name="pass" maxlength="25" id="password" onKeyUp="updatelength('password', 'pass_length')"><div id="pass_result"></div><br /><div id="pass_length"></div></td></tr>
        <tr><td>Confirm Password</td><td><input type="password" name="cpass" maxlength="25" id="c_password"></td></tr>
        <tr><td>Gender</td><td><select name="gender"><option value="1">male</option><option value="0">female</option></select></td></tr>
        <tr><td>Email</td><td><input type="text" name="email" maxlength="50" id="email" onKeyUp="updatelength('email', 'email_length')"><br /><div id="email_length"></div></td></tr>
        <tr><td colspan="2"><input type="submit" name="submit" value="Register"></td></tr>
    </table>
    <h3 id="results"></h3>
</form>

<form action="index.php" method="post" id="form" onsubmit="return validate_all('results');">
    <table cellspacing="10">
        <tr><td>Login</td><td><input type="text" name="login" maxlength="25" id="login" onKeyUp="updatelength('login', 'login_length')"><br /><div id="login_length"></div> </td></tr>
        <tr><td>Password</td><td><input type="password" name="pass" maxlength="25" id="password" onKeyUp="updatelength('password', 'pass_length')"><div id="pass_result"></div><br /><div id="pass_length"></div></td></tr>
        <tr><td>Confirm Password</td><td><input type="password" name="cpass" maxlength="25" id="c_password"></td></tr>
        <tr><td>Gender</td><td><select name="gender"><option value="1">male</option><option value="0">female</option></select></td></tr>
        <tr><td>Email</td><td><input type="text" name="email" maxlength="50" id="email" onKeyUp="updatelength('email', 'email_length')"><br /><div id="email_length"></div></td></tr>
        <tr><td colspan="2"><input type="submit" name="submit" value="Register"></td></tr>
    </table>
    <h3 id="results"></h3>
</form>

Things to note:

注意事项:

  • Don’t forget to name your text fields, otherwise you won’t be able to receive data from them later on.

    不要忘记命名您的文本字段,否则以后您将无法从它们接收数据。
  • Maxlength parameter reduces number of characters you can use in each text field.

    Maxlength参数减少了每个文本字段中可以使用的字符数。
  • Action, method and id parameters are required so place them into form tag.

    需要操作,方法和id参数,因此请将它们放入表单标签。
  • You can make table border visible by placing border=”1″ in table tag if you want to actually see the table.

    如果您想实际查看表格,可以通过在表格标签中放置border =“ 1”来使表格边框可见。

Here’s the code of second page:

这是第二页的代码:

templates / step2.html (templates/step2.html)


<h2>{errors}</h2>
<form action="index.php" method="post">
    <table cellspacing="10">
        <input type="hidden" name="login" value="{login}">
        <input type="hidden" name="pass" value="{pass}">
        <input type="hidden" name="cpass" value="{cpass}">
        <input type="hidden" name="gender" value="{gender}">
        <input type="hidden" name="email" value="{email}">
        <tr><td><span>Verification code</span></td><td><input name="vcode"></td><td></td></tr>
        <tr><td><span>Hint</span></td><td><i>{vcode}</i></td><td></td></tr>
        <tr><td colspan="2"><input type="submit" name="submit" value="Register"></td></tr>
    </table>
</form>

<h2>{errors}</h2>
<form action="index.php" method="post">
    <table cellspacing="10">
        <input type="hidden" name="login" value="{login}">
        <input type="hidden" name="pass" value="{pass}">
        <input type="hidden" name="cpass" value="{cpass}">
        <input type="hidden" name="gender" value="{gender}">
        <input type="hidden" name="email" value="{email}">
        <tr><td><span>Verification code</span></td><td><input name="vcode"></td><td></td></tr>
        <tr><td><span>Hint</span></td><td><i>{vcode}</i></td><td></td></tr>
        <tr><td colspan="2"><input type="submit" name="submit" value="Register"></td></tr>
    </table>
</form>

And – last one page:

并且–最后一页:

templates / step3.html (templates/step3.html)


<h1>Registration complete</h1>

<h1>Registration complete</h1>

第2步–添加CSS (Step 2 – Adding CSS)

Now we have our HTML form but it does not look attractively yet. As you may have guessed it is time to add some CSS and make our form look a little better. Here is my example of green form definitions:

现在我们有了我们HTML表单,但是看起来还没有吸引人。 您可能已经猜到了该添加一些CSS并使我们的表单看起来更好的时候了。 这是我的绿色表单定义示例:

css / main.css (css/main.css)


form {
    background-color: #555;
    display: block;
    padding: 15px;
}
input[type=text], input[type=password], input[type=submit] {
    -moz-border-radius: 2px;
    -ms-border-radius: 2px;
    -o-border-radius: 2px;
    -webkit-border-radius: 2px;
    border-radius: 2px;
}
input[type=text], input[type=password], select {
    background-color: rgb(246, 254, 231);
    border-color: rgb(180, 207, 94);
    border-style: solid;
    border-width: 1px;
    font-size: 16px;
    height: 25px;
    margin-right: 10px;
    width: 200px;
}
input[type=submit]{
    cursor: pointer;
    font-size: 16px;
    height: 35px;
    padding: 5px;
}
input.wrong {
    border-color: rgb(180, 207, 94);
    background-color: rgb(255, 183, 183);
}
input.correct {
    border-color: rgb(180, 207, 94);
    background-color: rgb(220, 251, 164);
}
#pass_result {
    float: right;
}

form {
    background-color: #555;
    display: block;
    padding: 15px;
}
input[type=text], input[type=password], input[type=submit] {
    -moz-border-radius: 2px;
    -ms-border-radius: 2px;
    -o-border-radius: 2px;
    -webkit-border-radius: 2px;
    border-radius: 2px;
}
input[type=text], input[type=password], select {
    background-color: rgb(246, 254, 231);
    border-color: rgb(180, 207, 94);
    border-style: solid;
    border-width: 1px;
    font-size: 16px;
    height: 25px;
    margin-right: 10px;
    width: 200px;
}
input[type=submit]{
    cursor: pointer;
    font-size: 16px;
    height: 35px;
    padding: 5px;
}
input.wrong {
    border-color: rgb(180, 207, 94);
    background-color: rgb(255, 183, 183);
}
input.correct {
    border-color: rgb(180, 207, 94);
    background-color: rgb(220, 251, 164);
}
#pass_result {
    float: right;
}

Classes are named according to their further function. For example .wrong class will be used when text field contains wrong informations and so on. Also you should now add class parameter to each text field and elements that should have some style. To do it place class=”class_name_here” to input tags where class_name_here is name of class defined between style tags (see example if you are new to adding classes to elements). Add only field class to each text field, rest will be used later. I advise to modify styles a little by choosing different colors and values so that they could fulfill your requirements.

类是根据其进一步的功能命名的。 例如,当文本字段包含错误信息等时,将使用.wrong类。 另外,您现在还应该向每个文本字段和应具有某种样式的元素添加类参数。 为此,将class =“ class_name_here”放置到输入标签中,其中class_name_here是在样式标签之间定义的类的名称(如果您不熟悉向元素添加类,请参见示例)。 仅将字段类添加到每个文本字段,其余部分将在以后使用。 我建议您通过选择不同的颜色和值来稍微修改样式,以便它们可以满足您的要求。

步骤3 – Javascript (Step 3 – Javascript)

This step will be about dynamic elements and how to use Javascript to create and then apply them wherever you would like to. After observing what some sites do I’ve noticed that there are plenty of such scripts (which I’m going to present here) recently, especially on big companies/corporations sites and popular services so I think this really make users happier and encourage them to fill forms in. Look around and check out some sign up forms (Google.com, Yahoo.com and flickr.com, ebay.com… yes, dynamic forms are almost everywhere now). Some easy to do scripts can reduce number of unnecessary clicks and let users create account (or whatever you are making form for) more quickly than before, not to mention they look much more prettily and cool. There are various places to put the javascript code as it was with CSS. It can either be written inside the main_page.html file using a tag or put to the other file and then include this file to main_page.html. Both case will use the same code to put scripts to your document. I chose second option so make separated script file (js/script.js) for our main_page.html file.

此步骤将涉及动态元素以及如何使用Javascript创建然后将其应用到任何您想要的地方。 在观察了一些网站之后,我注意到最近有很多这样的脚本(我将在这里展示),尤其是在大型公司/公司网站和受欢迎的服务上,因此我认为这确实使用户更加满意并鼓励他们填写表格。四处看看并签出一些注册表格(Google.com,Yahoo.com和flickr.com,ebay.com…是的,动态表格现在几乎无处不在)。 一些易于执行的脚本可以减少不必要的点击次数,并使用户比以前更快地创建帐户(或您要为其创建表单的任何内容),更不用说它们看起来更加漂亮和酷。 有很多地方可以放置JavaScript代码,就像使用CSS一样。 可以使用标签将其写入main_page.html文件中,也可以放置到其他文件中,然后将该文件包含在main_page.html中 。 两种情况都将使用相同的代码将脚本放入文档中。 我选择了第二个选项,因此请为main_page.html文件创建单独的脚本文件(js / script.js)。

Each function from further steps should be placed where I made comment so between.

后续步骤中的每个功能都应放在我之间发表评论的位置。

步骤4 –应用功能 (Step 4 – Applying functions)

This is very important step so read it carefully. Adding javascript functions to your HTML form elements should be easy because it is very similar to adding CSS classes to them. Also to make it easier I tried to create functions from further steps alike to each other so that you can apply them almost the same way but for sure I will add some sample files each step to show you how it is made and I will write a little explanation to them. Generally if you want to add function (let’s say updatelength() from Step 7 – Counter) to login field you should replace:

这是非常重要的步骤,因此请仔细阅读。 向HTML表单元素添加javascript函数应该很容易,因为它与向其添加CSS类非常相似。 另外,为了使操作更容易,我尝试通过彼此类似的步骤来创建函数,以便您几乎可以以相同的方式应用它们,但是可以肯定的是,我将在每个步骤中添加一些示例文件以向您展示其制作方法,并编写一个给他们一点解释。 通常,如果您想向登录字段添加功能(例如,从步骤7 – Counter开始的 updatelength() ),则应替换为:


    <input type="text" name="login" maxlength="25" id="login">

    <input type="text" name="login" maxlength="25" id="login">

with:

与:


    <input type="text" name="login" maxlength="25" id="login" onKeyUp="updatelength('login', 'login_length')"><br /><div id="login_length"></div>

    <input type="text" name="login" maxlength="25" id="login" onKeyUp="updatelength('login', 'login_length')"><br /><div id="login_length"></div>

The only thing that has changed is onKeyUp=”updatelength(‘logid’, ‘login_length’)” was added. Well, if we add something like this to our input we will observe what function is returning outcome in div tag with id “login_length”.

唯一更改的是添加了onKeyUp =“ updatelength('logid','login_length')” 。 好吧,如果我们在输入中添加类似的内容,我们将观察到哪些函数在id为“ login_length”的div标签中返回结果。

Why?

为什么?

Because updatelength() function starts like this “function updatelength(field, output){…” (Step 7 – Counter) and that means it requires two arguments which are ID OF TEXT FIELD IN HTML and ID OF DIV WHERE RESULT WILL BE. Now it is easy, isn’t it? :) Rest of functions are similar to this one so I hope it won’t be a problem to apply it. Each one needs almost same values as arguments. Notes:

因为updatelength()函数像这样“函数updatelength(field,output){…” (步骤7 –计数器)开始,这意味着它需要两个参数,即HTML中的文本字段 ID结果将是DIV的ID 。 现在很容易,不是吗? :)其余功能与这一功能相似,所以我希望应用它不会有问题。 每个参数都需要几乎相同的值作为参数。 笔记:

  • You can use more than one function to one text field by using a separator “;”. Example: onKeyUp=”updatelength(‘logid’, ‘login_length’); valid_length(‘logid’, ‘login_o’);”

    通过使用分隔符“;”,可以对一个文本字段使用多个功能。 示例: onKeyUp =” updatelength('logid','login_length'); valid_length('logid','login_o');”

  • Look up to the source of example sites if you have any problems.

    如果有任何问题,请查阅示例站点的来源。

步骤5 –计数器 (Step 5 – Counter)

So, here goes first script to improve our sign up form. It can be used in many other cases like adding a comment or posting message somewhere so you can attach it to more than one form. It will count characters we typed and tells us how many more we can write to the end of field. Short code and useful thing:

因此,这里是第一个脚本来改进我们的注册表单。 它可以在许多其他情况下使用,例如添加评论或在某处张贴消息,以便可以将其附加到多个表单上。 它将计算我们键入的字符,并告诉我们可以写多少个字符到字段末尾。 短代码和有用的东西:


function updatelength(field, output){
    curr_length = document.getElementById(field).value.length;
    field_mlen = document.getElementById(field).maxLength;
    document.getElementById(output).innerHTML = curr_length+'/'+field_mlen;
    return 1;
}

function updatelength(field, output){
    curr_length = document.getElementById(field).value.length;
    field_mlen = document.getElementById(field).maxLength;
    document.getElementById(output).innerHTML = curr_length+'/'+field_mlen;
    return 1;
}

Once you have placed it, you can run it using method presented in previous step (also there is example of usage described). This script checks how many characters did you use (each time you use one) and how many are allowed by text field’s maxlength parameter, then it changes value between the div tags. There are 2 variables called ‘curr_length’ and ‘field_mlen’. First one gets and store number of characters you’ve typed (as I already wrote each time you type something in the field) and second one stores value of maxlength parameter of the field on which you are using this function. Then it simply shows both values with ‘/’ separator in the middle. Note:

放置后,可以使用上一步中介绍的方法来运行它(还有描述的用法示例)。 该脚本检查您使用了多少个字符(每次使用一个)以及文本字段的maxlength参数允许多少个字符,然后在div标记之间更改了值。 有两个变量,分别为'curr_length''field_mlen' 。 第一个获取并存储您键入的字符数(就像我每次在字段中键入内容时所写的那样),第二个存储您正在使用此函数的字段的maxlength参数值。 然后,它只显示两个值,中间用'/'分隔符。 注意:

  • I applied this script to every field

    我将此脚本应用于每个领域

步骤6 –密码强度 (Step 6 – Password Strength)

Now it will be something which will check for how strong the password is. Scripts like this are usually not very extended so here is the basic version of it:

现在将检查密码的强度。 像这样的脚本通常不是很扩展,所以这里是它的基本版本:


function check_v_pass(field, output) {
    pass_buf_value = document.getElementById(field).value;
    pass_level = 0;
    if (pass_buf_value.match(/[a-z]/g)) {
        pass_level++;
    }
    if (pass_buf_value.match(/[A-Z]/g)) {
        pass_level++;
    }
    if (pass_buf_value.match(/[0-9]/g)) {
        pass_level++;
    }
    if (pass_buf_value.length < 5) {
        if(pass_level >= 1) pass_level--;
    } else if (pass_buf_value.length >= 20) {
        pass_level++;
    }
    output_val = '';
    switch (pass_level) {
        case 1: output_val='Weak'; break;
        case 2: output_val='Normal'; break;
        case 3: output_val='Strong'; break;
        case 4: output_val='Very strong'; break;
        default: output_val='Very weak'; break;
    }
    if (document.getElementById(output).value != pass_level) {
        document.getElementById(output).value = pass_level;
        document.getElementById(output).innerHTML = output_val;
    }
    return 1;
}

function check_v_pass(field, output) {
    pass_buf_value = document.getElementById(field).value;
    pass_level = 0;
    if (pass_buf_value.match(/[a-z]/g)) {
        pass_level++;
    }
    if (pass_buf_value.match(/[A-Z]/g)) {
        pass_level++;
    }
    if (pass_buf_value.match(/[0-9]/g)) {
        pass_level++;
    }
    if (pass_buf_value.length < 5) {
        if(pass_level >= 1) pass_level--;
    } else if (pass_buf_value.length >= 20) {
        pass_level++;
    }
    output_val = '';
    switch (pass_level) {
        case 1: output_val='Weak'; break;
        case 2: output_val='Normal'; break;
        case 3: output_val='Strong'; break;
        case 4: output_val='Very strong'; break;
        default: output_val='Very weak'; break;
    }
    if (document.getElementById(output).value != pass_level) {
        document.getElementById(output).value = pass_level;
        document.getElementById(output).innerHTML = output_val;
    }
    return 1;
}

As a ‘field’ argument we should put an ID of field to check and in ‘output’ goes place where the result will be shown. Of course DON’T TYPE IT HERE but when you are using this function (here you are only creating it) so replace values only when you write OnKeyUp="… in your input :). Function also here contains two variables. First one called ‘pass_level’ contains current password strength and it is set to 0 by default because password field is empty at the beginning. Second variable named ‘pass_buf_value’ contains current value of your password field. Below those two you can see some if()-s, they are looking for some characters that may increase password strength level and if one of them find anything it updates value of ‘pass_level’ variable by adding 1 to it. Of course rest of the script returns proper informations, it chooses right text depending on current ‘pass_level’ value. Apply this script to your password field.

作为“字段”参数,我们应检查字段ID,然后在“输出”中显示结果的位置。 当然不要在这里键入内容,但是当您使用此函数时(此处仅创建它),因此仅当在输入中写入OnKeyUp =“…时才替换值。)此函数还包含两个变量,第一个称为'pass_level'包含当前密码强度,默认情况下设置为0,因为password字段开头是空的。第二个名为'pass_buf_value'的变量包含密码字段的当前值。在这两个变量下面可以看到一些if()-s ,他们正在寻找一些可能会提高密码强度级别的字符,如果其中之一发现它可以通过加1来更新'pass_level'变量的值,当然脚本的其余部分会返回正确的信息,它会根据情况选择正确的文本当前的“ pass_level”值。将此脚本应用于您的密码字段。

步骤7 –比较密码 (Step 7 – Comparing passwords)

Third script compare value from password field with value from confirm password field to make user sure, he typed exactly what he wanted. Characters here are not visible so to check if user did not make any mistakes we need two different fields and both has to contain same values when typing, only then form is filled correctly:

第三个脚本将“密码”字段中的值与“确认密码”字段中的值进行比较,以确保用户确定自己输入的确切内容。 此处的字符不可见,因此要检查用户是否未犯任何错误,我们需要两个不同的字段,并且在键入时都必须包含相同的值,只有这样才能正确填写表单:


function compare_valid(field, field2) {
    fld_val = document.getElementById(field).value;
    fld2_val = document.getElementById(field2).value;
    if (fld_val == fld2_val) {
        update_css_class(field2, 2);
        p_valid_r = 1;
    } else {
        update_css_class(field2, 1);
        p_valid_r = 0;
    }
    return p_valid_r;
}

function compare_valid(field, field2) {
    fld_val = document.getElementById(field).value;
    fld2_val = document.getElementById(field2).value;
    if (fld_val == fld2_val) {
        update_css_class(field2, 2);
        p_valid_r = 1;
    } else {
        update_css_class(field2, 1);
        p_valid_r = 0;
    }
    return p_valid_r;
}

Guess how to use it? Only tip I will give you is that you should use it only on the compare password field and nowhere else. Well, this script as you can see arrogates values of 2 fields to two different variables called ‘fld_val’ and ‘fld2_val’. There is an if() construction below them which compares those two values and changes between 2 versions of style (green when everything is good and red when there are any errors).

猜猜怎么用? 我给您的唯一提示是,您只能在“ 比较密码”字段上使用它,而不能在其他地方使用它。 好吧,正如您所见,该脚本将2个字段的值代入两个名为'fld_val''fld2_val'的不同变量。 在它们下面有一个if()构造,它比较这两个值并在两种样式的样式之间进行更改(如果一切正常,则为绿色,如果有任何错误,则为红色)。

步骤8 –电子邮件验证 (Step 8 – Email verification)

A bit more complicated script but usage is easy as always. Every email address must fulfill following criteria: 1. Must have some characters at the beginning (letters or numbers (and some less important)) 2. Must have @ (at) character 3. Must have domain name a) Must have first word b) Must have . (dot) character c) Must have second word 4. And in the event that somebody believe his email address contains big letters it must convert characters to small ones

脚本稍微复杂一点,但是用法和以往一样容易。 每个电子邮件地址必须满足以下条件:1.开头必须有一些字符(字母或数字(有些不太重要))2.必须有@(@)字符3.必须具有域名a)必须有第一个单词b ) 一定有 。 (点)字符c)必须有第二个单词4。如果有人认为他的电子邮件地址包含大写字母,则必须将其转换为小写字母


function check_v_mail(field) {
    fld_value = document.getElementById(field).value;
    is_m_valid = 0;
    if (fld_value.indexOf('@') >= 1) {
        m_valid_dom = fld_value.substr(fld_value.indexOf('@')+1);
        if (m_valid_dom.indexOf('@') == -1) {
            if (m_valid_dom.indexOf('.') >= 1) {
                m_valid_dom_e = m_valid_dom.substr(m_valid_dom.indexOf('.')+1);
                if (m_valid_dom_e.length >= 1) {
                    is_m_valid = 1;
                }
            }
        }
    }
    if (is_m_valid) {
        update_css_class(field, 2);
        m_valid_r = 1;
    } else {
        update_css_class(field, 1);
        m_valid_r = 0;
    }
    return m_valid_r;
}

function check_v_mail(field) {
    fld_value = document.getElementById(field).value;
    is_m_valid = 0;
    if (fld_value.indexOf('@') >= 1) {
        m_valid_dom = fld_value.substr(fld_value.indexOf('@')+1);
        if (m_valid_dom.indexOf('@') == -1) {
            if (m_valid_dom.indexOf('.') >= 1) {
                m_valid_dom_e = m_valid_dom.substr(m_valid_dom.indexOf('.')+1);
                if (m_valid_dom_e.length >= 1) {
                    is_m_valid = 1;
                }
            }
        }
    }
    if (is_m_valid) {
        update_css_class(field, 2);
        m_valid_r = 1;
    } else {
        update_css_class(field, 1);
        m_valid_r = 0;
    }
    return m_valid_r;
}

Place OnKeyUp="… into input tag where email address is and create new div with adequate ID to make it work. This function basically looks up if the email address is typed correctly. First it arrogates value of the field to ‘fld_value’ variable to work with it. Everything is supervised by 4 if() constructions. They are step by step checking if there is @ symbol (1), then if it is on the second or further position (2). At the end if there is "dot" character after @ symbol (3) and finally if there are any characters before and after this "dot" (4). If any of if()-a find error it stops script and switches to red style wrong style of field. Those if()-s are a bit complicated as you can see but finally result is same as always, it chooses between green and red style and then shows it. Second part of this script is similar to switching between two options in already explained part so it should be clear for now.

OnKeyUp =“…放入电子邮件地址所在的输入标记中,并创建具有足够ID的新div以使其正常工作。该功能基本上是在电子邮件地址键入正确的情况下进行查找。首先,将字段值设置为'fld_value'变量,一切都由4个if()构造监督。它们会逐步检查是否有@符号(1),然后在第二个或另一个位置(2)。最后是否有“ @符号(3)之后的“点”字符,最后在该“点”之前和之后的字符(4)。如果if()-查找错误,它将停止脚本并切换为红色样式错误的字段。如您所见,那些if()-s有点复杂,但最终结果仍然与往常一样,它在绿色和红色样式之间进行选择,然后显示出来。该脚本的第二部分类似于在已经说明的部分中的两个选项之间进行切换所以现在应该很清楚。

步骤9 –空字段 (Step 9 – Empty fields)

Short function checking if there is more than 0 characters in our inputs. If there are empty spaces somewhere we can’t create new account:

短函数检查输入中的字符是否超过0。 如果某处有空白,我们将无法创建新帐户:


function valid_length(field) {
    length_df = document.getElementById(field).value.length;
    if (length_df >= 1 && length_df <= document.getElementById(field).maxLength) {
        update_css_class(field, 2);
        ret_len = 1;
    } else {
        update_css_class(field, 1);
        ret_len = 0;
    }
    return ret_len;
}

function valid_length(field) {
    length_df = document.getElementById(field).value.length;
    if (length_df >= 1 && length_df <= document.getElementById(field).maxLength) {
        update_css_class(field, 2);
        ret_len = 1;
    } else {
        update_css_class(field, 1);
        ret_len = 0;
    }
    return ret_len;
}

Like usually here also we have to give a text field ID and ID of div where result of script should be as an arguments. Add this script to each field (except gender one). This one has only one interesting part to explain because rest should be clear for you already. I’m talking about this long if() construction in the third line. It first checks if value of the field has at least one character and than in its second part if it has no more than ‘max number’ of characters. Then it just changes between two options – right and wrong.

像通常在这里一样,我们还必须提供文本字段ID和div ID,其中脚本结果应作为参数。 将此脚本添加到每个字段(性别除外)。 这一部分只有一个有趣的部分可以解释,因为休息对您来说应该已经很清楚了。 我在第三行中谈论的是漫长的if()构造。 它首先检查字段的值是否至少包含一个字符,如果不超过“最大数量”个字符,则检查其第二部分。 然后,它只是在两个选项之间切换–是非。

步骤10 –着色 (Step 10 – Coloring)

This one is very short and only changes mode between two classes to make better visual effects. Classes must be defined in our CSS part of document (they are if you copied definitions from step 4). I called them wrong and correct:

这个很短,只有在两个类之间更改模式才能获得更好的视觉效果。 必须在文档CSS部分中定义类(如果您从第4步中复制了定义,则为类)。 我称他们为错误正确的


function update_css_class(field, class_index) {
    if (class_index == 1) {
        class_s = 'wrong';
    } else if (class_index == 2) {
        class_s = 'correct';
    }
    document.getElementById(field).className = class_s;
    return 1;
}

function update_css_class(field, class_index) {
    if (class_index == 1) {
        class_s = 'wrong';
    } else if (class_index == 2) {
        class_s = 'correct';
    }
    document.getElementById(field).className = class_s;
    return 1;
}

As you may have already noticed this function is ran by other ones. Previous and further scripts puts arguments here. First argument is an ID of field you are currently working with and second is number 1 or 2. This numbers are being changed depending on actual field status to let then change its style to correct one. Let’s continue to next step.

您可能已经注意到此功能是由其他功能运行的。 先前的脚本和其他脚本在此处放置参数。 第一个参数是您当前正在使用的字段的ID,第二个参数是数字1或2。此数字将根据字段的实际状态进行更改,然后更改其样式以更正它。 让我们继续下一步。

步骤11 –最后JavaScript验证 (Step 11 – Last Javascript verification)

This is the last script using javascript. It calls out every function once more for sure and returns encountered errors or allows us to continue. It does not require refreshing whole page but check form quickly after pressing "Register". That’s very important script and other ones were mostly make to let this one work:

这是使用javascript的最后一个脚本。 它会再次确定每个函数,并返回遇到的错误或允许我们继续。 它不需要刷新整个页面,而是在按***册”后Swift检查表单。 这是非常重要的脚本,而其他大多数脚本都是为了使这一脚本起作用:


function validate_all(output) {
    t1 = valid_length('login');
    t2 = valid_length('password');
    t3 = compare_valid('password', 'c_password');
    t4 = check_v_mail('email');
    t5 = check_v_pass('password', 'pass_result');
    errorlist = '';
    if (! t1) {
        errorlist += 'Login is too short/long<br />';
    }
    if (! t2) {
        errorlist += 'Password is too short/long<br />';
    }
    if (! t3) {
        errorlist += 'Passwords are not the same<br />';
    }
    if (! t4) {
        errorlist += 'Mail is wrong<br />';
    }
    if (errorlist) {
        document.getElementById(output).innerHTML = errorlist;
        return false;
    }
    return true;
}

function validate_all(output) {
    t1 = valid_length('login');
    t2 = valid_length('password');
    t3 = compare_valid('password', 'c_password');
    t4 = check_v_mail('email');
    t5 = check_v_pass('password', 'pass_result');
    errorlist = '';
    if (! t1) {
        errorlist += 'Login is too short/long<br />';
    }
    if (! t2) {
        errorlist += 'Password is too short/long<br />';
    }
    if (! t3) {
        errorlist += 'Passwords are not the same<br />';
    }
    if (! t4) {
        errorlist += 'Mail is wrong<br />';
    }
    if (errorlist) {
        document.getElementById(output).innerHTML = errorlist;
        return false;
    }
    return true;
}

This script to work must be added to your submission form. And don’t forget to put div tag with ‘results’ id somewhere so that there outcome could go (in my case it is at the bottom of form so below just made ‘button’). Once you press new button this function recalls other functions from previous steps and checks once more for any mistakes for sure. If everything is fine it let you create account but if something is wrong it shows errors there where you’ve placed your ‘div’ with ‘results’ ID. Also in this script you can define your own error messages.

必须运行的脚本必须添加到您的提交表单中。 并且不要忘记将带有“结果” ID的div标记放在某个位置,以便可以进行结果输出(在我的情况下,它位于表格的底部,因此下面仅是“按钮”)。 按下新按钮后,此功能将调出先前步骤中的其他功能,并再次检查是否有任何错误。 如果一切正常,则可以创建帐户,但是如果出现问题,则在将“ div”“结果” ID放置在那里的地方显示错误。 另外,在此脚本中,您可以定义自己的错误消息。

步骤12 –最终验证 (Step 12 – Final verification)

From now it will be mostly about PHP (and MySQL) so if you don’t want to make such a form on you website you can just leave it and use methods I showed in other situations :) Otherwise if you would like to store account data using MySQL database continue reading. Javascript actually doesn’t protect our database from anything, it only makes people lifes easier :) If we want to be sure that filled form is 100% correct we must use PHP verification before we can add anything to our database – that is because if somebody will turn javascript off still he can write whatever he want while creating account and this may make database errors occurs. To add some very simply PHP script create index.php file which will be launched after pressing "Register" button. Well, here’s the code you should put to your index.php file:

从现在开始,它将主要是关于PHP(和MySQL)的,因此,如果您不想在您的网站上制作这样的表格,则可以保留它,并使用我在其他情况下展示的方法:)否则,如果您想存储帐户使用MySQL数据库的数据继续读取。 Javascript实际上并不能保护我们的数据库免受任何伤害,它只会使人们的生活变得更轻松:)如果我们要确保填充形式正确无误,则必须先使用PHP验证,然后才能向数据库中添加任何内容,这是因为有人将关闭javascript,他仍然可以在创建帐户时写任何内容,这可能会使数据库出错。 要添加一些非常简单PHP脚本,请创建index.php文件,该文件将在按***册”按钮后启动。 好吧,这是您应该放入index.php文件中的代码:

index.php (index.php)


<?php
// set error reporting level
if (version_compare(phpversion(), '5.3.0', '>=') == 1)
  error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
else
  error_reporting(E_ALL & ~E_NOTICE);
session_start();
if (isset($_POST['submit'])) {
    $sLogin = escape($_POST['login']);
    $sPass = escape($_POST['pass']);
    $sCPass = escape($_POST['cpass']);
    $sEmail = escape($_POST['email']);
    $iGender = (int)$_POST['gender'];
    $sErrors = '';
    if (strlen($sLogin) >= 1 and strlen($sLogin) <= 25) {
        if (strlen($sPass) >= 1 and strlen($sPass) <= 25) {
            if (strlen($sEmail) >= 1 and strlen($sEmail) <= 55) {
                if ($sPass == $sCPass) {
                    if (ereg('^[a-zA-Z0-9\-\.][email protected][a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$', $sEmail)) {
                        if ($iGender == '1' xor $iGender == '0') {
                            $sVcode = escape($_POST['vcode']);
                            if (! isset($_SESSION['valdiation_code'])) {
                                // Here you can send him some verification code (by email or any another ways)
                                $sCode = uniqid(rand(), true);
                                $_SESSION['valdiation_code'] = md5($sCode);
                            } elseif (md5($sVcode) == $_SESSION['valdiation_code']) {
                                // Here you can add him to database
                                // mysql_query('INSERT INTO ....
                                // display step 3 (final step)
                                echo strtr(file_get_contents('templates/step3.html'), array());
                                exit;
                            } else {
                                $sErrors = 'Verification code is wrong';
                            }
                        } else {
                            $sErrors = 'Gender is wrong';
                        }
                    } else {
                        $sErrors = 'Email is wrong';
                    }
                } else {
                    $sErrors = 'Passwords are not the same';
                }
            } else {
                $sErrors = 'Address email is too long';
            }
        } else {
            $sErrors = 'Password is too long';
        }
    } else {
        $sErrors = 'Login is too long';
    }
    // display step 2
    $aParams = array(
        '{errors}' => $sErrors,
        '{login}' => $sLogin,
        '{pass}' => $sPass,
        '{cpass}' => $sCPass,
        '{gender}' => $iGender,
        '{email}' => $sEmail,
        '{vcode}' => $sCode
    );
    echo strtr(file_get_contents('templates/step2.html'), $aParams);
    exit;
}
// unset validation code if exists
unset($_SESSION['valdiation_code']);
// draw registration page
echo strtr(file_get_contents('templates/main_page.html'), array());
// extra useful function to make POST variables more safe
function escape($s) {
    //return mysql_real_escape_string(strip_tags($s)); // uncomment in when you will use connection with database
    return strip_tags($s);
}

<?php
// set error reporting level
if (version_compare(phpversion(), '5.3.0', '>=') == 1)
  error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
else
  error_reporting(E_ALL & ~E_NOTICE);
session_start();
if (isset($_POST['submit'])) {
    $sLogin = escape($_POST['login']);
    $sPass = escape($_POST['pass']);
    $sCPass = escape($_POST['cpass']);
    $sEmail = escape($_POST['email']);
    $iGender = (int)$_POST['gender'];
    $sErrors = '';
    if (strlen($sLogin) >= 1 and strlen($sLogin) <= 25) {
        if (strlen($sPass) >= 1 and strlen($sPass) <= 25) {
            if (strlen($sEmail) >= 1 and strlen($sEmail) <= 55) {
                if ($sPass == $sCPass) {
                    if (ereg('^[a-zA-Z0-9\-\.][email protected][a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$', $sEmail)) {
                        if ($iGender == '1' xor $iGender == '0') {
                            $sVcode = escape($_POST['vcode']);
                            if (! isset($_SESSION['valdiation_code'])) {
                                // Here you can send him some verification code (by email or any another ways)
                                $sCode = uniqid(rand(), true);
                                $_SESSION['valdiation_code'] = md5($sCode);
                            } elseif (md5($sVcode) == $_SESSION['valdiation_code']) {
                                // Here you can add him to database
                                // mysql_query('INSERT INTO ....
                                // display step 3 (final step)
                                echo strtr(file_get_contents('templates/step3.html'), array());
                                exit;
                            } else {
                                $sErrors = 'Verification code is wrong';
                            }
                        } else {
                            $sErrors = 'Gender is wrong';
                        }
                    } else {
                        $sErrors = 'Email is wrong';
                    }
                } else {
                    $sErrors = 'Passwords are not the same';
                }
            } else {
                $sErrors = 'Address email is too long';
            }
        } else {
            $sErrors = 'Password is too long';
        }
    } else {
        $sErrors = 'Login is too long';
    }
    // display step 2
    $aParams = array(
        '{errors}' => $sErrors,
        '{login}' => $sLogin,
        '{pass}' => $sPass,
        '{cpass}' => $sCPass,
        '{gender}' => $iGender,
        '{email}' => $sEmail,
        '{vcode}' => $sCode
    );
    echo strtr(file_get_contents('templates/step2.html'), $aParams);
    exit;
}
// unset validation code if exists
unset($_SESSION['valdiation_code']);
// draw registration page
echo strtr(file_get_contents('templates/main_page.html'), array());
// extra useful function to make POST variables more safe
function escape($s) {
    //return mysql_real_escape_string(strip_tags($s)); // uncomment in when you will use connection with database
    return strip_tags($s);
}

Now, lets try to understand this. This script generally does EXACTLY the same what previous JS scripts did but it is launched on the server side to check everything once more. Continue reading to check how does it work.

现在,让我们尝试了解这一点。 该脚本通常与以前的JS脚本完全相同,但是在服务器端启动以再次检查所有内容。 继续阅读以检查其工作方式。

So, please pay attention to all our checks, and – to added validation functional. When our form submitted, the next step will contain single field to accept some validation code. Of course, for our demo page you always can see that checking code. But, as some suggestion – I can offer you to enable email confirmation (as example). So, you have to add email sending to this code also. And, only after accepting that extra validation code (if this code was right) – only then allow member registration. Please read my comments carefully.

因此,请注意我们所有的检查,以及–附加的验证功能。 提交表单后,下一步将包含单个字段以接受一些验证代码。 当然,对于我们的演示页面,您始终可以看到该检查代码。 但是,作为一些建议,我可以为您提供启用电子邮件确认的功能(例如)。 因此,您还必须添加发送至此代码的电子邮件。 而且,只有在接受了该额外的验证码(如果该验证码正确)之后,才允许成员注册。 请仔细阅读我的评论。

现场演示

结论 (Conclusion)

So that is all for now. In the final version I also added some classes which make table better positioned (stable) so make sure you’ve checked it out. While creating your own form you can expand it anyhow relying on what I wrote or try to use your imagination to create something better. Hope you enjoyed it. Good luck and welcome back!

现在就这些了。 在最终版本中,我还添加了一些类,这些类可以使表更好地定位(稳定),因此请确保已将其签出。 在创建自己的表单时,您可以依靠我编写的内容进行扩展,也可以尝试利用您的想象力来创建更好的表单。 希望你喜欢。 祝你好运,欢迎回来!

翻译自: https://www.script-tutorials.com/form-validation-with-javascript-and-php/