jquery表单验证_如何为表单制作平滑的jQuery验证器

慕光赫
2023-12-01

jquery表单验证

Today I will tell about jquery validator – how to build professional web forms with validation. I will use jQuery Validator Plugin for our tutorial. You can ask me – where I can use it? – Quite anywhere: login or join forms for your website, forms of adding content, different guest books or blocks for comments. Really many ways for using it. I already saw several projects where validation was at server side. And submit of form just reload whole page where we seens – are we made any errors or not. Sometimes webmasters using ajax to send data invisible to server for validation. But in most of cases, this is much faster just to check all entered information at user side (using javascript/jQuery). Just check these several demos – and I will explain how to use it.

今天,我将介绍jquery验证程序–如何使用验证构建专业的Web表单。 我将在本教程中使用jQuery Validator插件。 您可以问我-我可以在哪里使用它? –随处可见:登录或加入网站表单,添加内容表单,不同的留言簿或注释栏。 确实有很多使用方式。 我已经看到了几个在服务器端进行验证的项目。 提交表单只是重新加载我们看到的整个页面-我们是否犯了任何错误。 有时,网站管理员会使用ajax将不可见的数据发送到服务器进行验证。 但是在大多数情况下,这仅比在用户端检查所有输入的信息(使用javascript / jQuery)要快得多。 只需查看以下几个演示–我将解释如何使用它。

Here are samples and downloadable package:

以下是示例和可下载的软件包:

现场演示

[sociallocker]

[社交储物柜]

打包下载

[/sociallocker]

[/ sociallocker]

Ok, download the source files and lets start coding !

好的,下载源文件并开始编码!

步骤1. HTML (Step 1. HTML)

This is single HTML file with all 3 samples of our lesson

这是单个HTML文件,其中包含本课程的所有3个示例

index.html (index.html)


<script src="js/jquery.min.js"></script>
<script src="js/jquery.validator.js"></script>
<script src="js/main.js"></script>
<link rel="stylesheet" href="css/main.css" type="text/css" />
<link rel="stylesheet" href="css/jquery.validator.css" type="text/css" />
<div class="examples">
    <div class="example"><h2>jQuery validator - checking forms</h1></div>
    <div class="example" id="login_form">
        <h2>Sample 1 - login form</h2>
        <div><label>Username: </label> <input type="text" id="username" /><span id="vres_username" class="result"></span></div>
        <div><label>Password: </label> <input type="password" id="password" /><span id="vres_password" class="result"></span></div>
        <div><button>Login</button></div>
    </div>
    <div class="example" id="join_form">
        <h2>Sample 2 - join (registration) form</h2>
        <div><label>Username: </label> <input type="text" id="username" /><span id="vres_username" class="result"></span></div>
        <div><label>Password: </label> <input type="password" id="password" /><span id="vres_password" class="result"></span></div>
        <div><label>Email: </label> <input type="text" id="email" /><span id="vres_email" class="result"></span></div>
        <div><label>DateOfBirth: </label> <input type="text" id="date"><span id="vres_date" class="result">possible formats: mm/dd/yyyy, mm-dd-yyyy, mm.dd.yyyy, mm dd yyyy</span></div>
        <div><button>Join</button></div>
    </div>
    <div class="example" id="news_form">
        <h2>Sample 3 - Adding news</h2>
        <div><label>Title: </label> <input type="text" id="title" /><span id="vres_title" class="result"></span></div>
        <div><label>News text: </label> <textarea id="text" style="width:300px;height:200px;"></textarea><span id="vres_text" class="result"></span></div>
        <div><button>Submit</button></div>
    </div>
    <div style="clear:both"></div>
</div>

<script src="js/jquery.min.js"></script>
<script src="js/jquery.validator.js"></script>
<script src="js/main.js"></script>
<link rel="stylesheet" href="css/main.css" type="text/css" />
<link rel="stylesheet" href="css/jquery.validator.css" type="text/css" />
<div class="examples">
    <div class="example"><h2>jQuery validator - checking forms</h1></div>
    <div class="example" id="login_form">
        <h2>Sample 1 - login form</h2>
        <div><label>Username: </label> <input type="text" id="username" /><span id="vres_username" class="result"></span></div>
        <div><label>Password: </label> <input type="password" id="password" /><span id="vres_password" class="result"></span></div>
        <div><button>Login</button></div>
    </div>
    <div class="example" id="join_form">
        <h2>Sample 2 - join (registration) form</h2>
        <div><label>Username: </label> <input type="text" id="username" /><span id="vres_username" class="result"></span></div>
        <div><label>Password: </label> <input type="password" id="password" /><span id="vres_password" class="result"></span></div>
        <div><label>Email: </label> <input type="text" id="email" /><span id="vres_email" class="result"></span></div>
        <div><label>DateOfBirth: </label> <input type="text" id="date"><span id="vres_date" class="result">possible formats: mm/dd/yyyy, mm-dd-yyyy, mm.dd.yyyy, mm dd yyyy</span></div>
        <div><button>Join</button></div>
    </div>
    <div class="example" id="news_form">
        <h2>Sample 3 - Adding news</h2>
        <div><label>Title: </label> <input type="text" id="title" /><span id="vres_title" class="result"></span></div>
        <div><label>News text: </label> <textarea id="text" style="width:300px;height:200px;"></textarea><span id="vres_text" class="result"></span></div>
        <div><button>Submit</button></div>
    </div>
    <div style="clear:both"></div>
</div>

步骤2. CSS (Step 2. CSS)

Here are 2 used CSS files. Just few styles for our demo page:

这是2个使用过CSS文件。 我们的演示页面只有几种样式:

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


body{background:#eee;font-family:Verdana, Helvetica, Arial, sans-serif;margin:0;padding:0}
.examples{background:#FFF;width:900px;font-size:80%;border:1px #000 solid;margin:3.5em auto 2em;padding:1em 2em 2em}
.examples .example{margin-bottom:15px;border-bottom:1px solid #DDD}
.examples .example div{margin-bottom:5px;}
.examples .example .result {margin-left:10px;}

body{background:#eee;font-family:Verdana, Helvetica, Arial, sans-serif;margin:0;padding:0}
.examples{background:#FFF;width:900px;font-size:80%;border:1px #000 solid;margin:3.5em auto 2em;padding:1em 2em 2em}
.examples .example{margin-bottom:15px;border-bottom:1px solid #DDD}
.examples .example div{margin-bottom:5px;}
.examples .example .result {margin-left:10px;}

css / jquery.validator.css (css/jquery.validator.css)


.validator_error{background:#FF7C8A;border:1px #9D0505 solid;color:#000}

.validator_error{background:#FF7C8A;border:1px #9D0505 solid;color:#000}

步骤3. JS (Step 3. JS)

Of course, here are used jQuery file: jquery.min.js and new library: jquery.validator.js. I don`t will include its sources directly in this post – both files available in package. Last file most interesting:

当然,这里使用的是jQuery文件:jquery.min.js和新库:jquery.validator.js。 我不会在这篇文章中直接提供其来源-这两个文件都在软件包中。 最后一个文件最有趣:

inc / main.js (inc/main.js)


$(function() {
    // sample 1 - login form
    $('#login_form #username').validator({
        format: 'alphanumeric',
        invalidEmpty: true,
        correct: function() {
            $('#login_form #vres_username').text('Thanks');
        },
        error: function() {
            $('#login_form #vres_username').text('Plese fill username field');
        }
    });
    $('#login_form #password').validator({
        format: 'alphanumeric',
        invalidEmpty: true,
        correct: function() {
            $('#vres_password').text('Thanks');
        },
        error: function() {
            $('#vres_password').text('Plese fill password field');
        }
    });
    // sample 2 - join form
    $('#join_form #username').validator({
        format: 'alphanumeric',
        invalidEmpty: true,
        correct: function() {
            $('#join_form #vres_username').text('Thanks');
        },
        error: function() {
            $('#join_form #vres_username').text('Plese fill your username');
        }
    });
    $('#join_form #password').validator({
        format: 'alphanumeric',
        invalidEmpty: true,
        correct: function() {
            $('#join_form #vres_password').text('Thanks');
        },
        error: function() {
            $('#join_form #vres_password').text('Plese fill password');
        }
    });
    $('#join_form #email').validator({
        format: 'email',
        invalidEmpty: true,
        correct: function() {
            $('#join_form #vres_email').text('Thanks');
        },
        error: function() {
            $('#join_form #vres_email').text('Please fill correct email');
        }
    });
    $('#join_form #date').validator({
        format: 'date',
        invalidEmpty: true,
        correct: function() {
            $('#vres_date').text('Thanks');
        },
        error: function() {
            $('#vres_date').text('Please fill correct date (in format: mm/dd/yyyy, mm-dd-yyyy, mm.dd.yyyy, mm dd yyyy)');
        }
    });
    // sample 3 - adding news form
    $('#news_form #title').validator({
        format: 'alphanumeric',
        invalidEmpty: true,
        correct: function() {
            $('#news_form #vres_title').text('Thanks');
        },
        error: function() {
            $('#news_form #vres_title').text('Plese fill title');
        }
    });
    $('#news_form #text').validator({
        minLength: 5,
        maxLength: 255,
        invalidEmpty: true,
        correct: function() {
            $('#news_form #vres_text').text('Thanks');
        },
        error: function() {
            $('#news_form #vres_text').text('Length of news text should be between 5 and 255 symbols');
        }
    });
});

$(function() {
    // sample 1 - login form
    $('#login_form #username').validator({
        format: 'alphanumeric',
        invalidEmpty: true,
        correct: function() {
            $('#login_form #vres_username').text('Thanks');
        },
        error: function() {
            $('#login_form #vres_username').text('Plese fill username field');
        }
    });
    $('#login_form #password').validator({
        format: 'alphanumeric',
        invalidEmpty: true,
        correct: function() {
            $('#vres_password').text('Thanks');
        },
        error: function() {
            $('#vres_password').text('Plese fill password field');
        }
    });
    // sample 2 - join form
    $('#join_form #username').validator({
        format: 'alphanumeric',
        invalidEmpty: true,
        correct: function() {
            $('#join_form #vres_username').text('Thanks');
        },
        error: function() {
            $('#join_form #vres_username').text('Plese fill your username');
        }
    });
    $('#join_form #password').validator({
        format: 'alphanumeric',
        invalidEmpty: true,
        correct: function() {
            $('#join_form #vres_password').text('Thanks');
        },
        error: function() {
            $('#join_form #vres_password').text('Plese fill password');
        }
    });
    $('#join_form #email').validator({
        format: 'email',
        invalidEmpty: true,
        correct: function() {
            $('#join_form #vres_email').text('Thanks');
        },
        error: function() {
            $('#join_form #vres_email').text('Please fill correct email');
        }
    });
    $('#join_form #date').validator({
        format: 'date',
        invalidEmpty: true,
        correct: function() {
            $('#vres_date').text('Thanks');
        },
        error: function() {
            $('#vres_date').text('Please fill correct date (in format: mm/dd/yyyy, mm-dd-yyyy, mm.dd.yyyy, mm dd yyyy)');
        }
    });
    // sample 3 - adding news form
    $('#news_form #title').validator({
        format: 'alphanumeric',
        invalidEmpty: true,
        correct: function() {
            $('#news_form #vres_title').text('Thanks');
        },
        error: function() {
            $('#news_form #vres_title').text('Plese fill title');
        }
    });
    $('#news_form #text').validator({
        minLength: 5,
        maxLength: 255,
        invalidEmpty: true,
        correct: function() {
            $('#news_form #vres_text').text('Thanks');
        },
        error: function() {
            $('#news_form #vres_text').text('Length of news text should be between 5 and 255 symbols');
        }
    });
});

In this file I draw rules of validation of all my 3 forms. Hope this is very easy to understand how to use it.

在此文件中,我绘制了所有3种形式的验证规则。 希望这是很容易理解的用法。

Its very easy to add new rule to any new field, just call ‘validator’ function with set of params for that field. Validator itself support next formats: Alphanumeric, Credit Card, Email, Date, Date and Time, Decimal, IP Address, Numeric, Phone, Zip Codes (US and Canada)

将新规则添加到任何新字段非常容易,只需使用该字段的参数集调用“验证器”功能即可。 验证程序本身支持以下格式:字母数字,信用卡,电子邮件,日期,日期和时间,十进制,IP地址,数字,电话,邮政编码(美国和加拿大)

Here are all necessay info about params of this library:

以下是有关此库参数的所有必要信息:

Param nameTypeDefault
className – class name for error elements.stringvalidator_error
trigger – list of events which will trigger on validation (separated by space).stringchange blur
format – format of the field. Table below will tell its detailsstringnull
invalidEmpty – invalid if empty? if yes(true) – it will generate error when it empty.boolfalse
minLength – min length for valid case.integernull
maxLength – max length for valid case.integernull
minValue – min value for element (for numbers only).integernull
maxValue – max value for element (for numbers only).integernull
contains – if element will contain this text – it will valid.string, regexpnull
notContains – if element will Not contain this text – it will valid.string, regexpnull
equals – if not null, value of element should be equal to this parameter to be valid.stringnull
notEquals – if not null, value of element should be Not equal to this parameter to be valid.stringnull
checked – (for checkboxes). to be valid = it thould be true (checking for check/uncheck state)boolnull
参数名称 类型 默认
className –错误元素的类名称。 验证错误
触发器 –将在验证时触发的事件列表(以空格分隔)。 改变模糊
格式 –字段格式。 下表将说明其详细信息 空值
invalidEmpty –如果为空则无效? 如果是(真)–空时将生成错误。 布尔
minLength –有效情况的最小长度。 整数 空值
maxLength –有效大小写的最大长度。 整数 空值
minValue –元素的最小值(仅适用于数字)。 整数 空值
maxValue –元素的最大值(仅适用于数字)。 整数 空值
包含 –如果element将包含此文本–将有效。 字符串,正则表达式 空值
notContains –如果element将不包含此文本–将有效。 字符串,正则表达式 空值
等于 –如果不为null,则element的值应等于此参数才有效。 空值
notEquals –如果不为null,则element的值应不等于此参数才有效。 空值
已选中 –(用于复选框)。 有效=它应该为真(检查检查/取消检查状态) 布尔 空值

format param types:

格式参数类型:

NameExamples
email – checking for Emails.email@domain.com
ip – checking for IP addresses.0.0.0.0 – 255.255.255.255
date – checking for Dates.mm/dd/yyyy, mm-dd-yyyy, mm.dd.yyyy, mm dd yyyy
datetime – checking for Datetimes.hh:mm, hh.mm, hh-mm, hh mm (with combination with dd,mm,yyyy)
phone – checking for Phones.555999888777 (10-15 digits)
zipUS – checking for US zip codes.12345-5555 (5 or 9 digit formats)
zipCanada – checking for Canada zip codes.K1A 0B1
creditCard – checking for Credit card number.4111111111111111 (13-16 digits)
numeric – checking for Digits.0-9
decimal – checking for Decimals.100,100.50
alphanumeric – checking for Text.a-zA-Z -_. (commonly – all UTF8 symbols)
名称 例子
电子邮件 –检查电子邮件。 email@domain.com
ip –检查IP地址。 0.0.0.0 – 255.255.255.255
日期 –检查日期。 mm / dd / yyyy,mm-dd-yyyy,mm.dd.yyyy,mm dd yyyy
datetime –检查日期时间。 hh:mm,hh.mm,hh-mm,hh mm(与dd,mm,yyyy结合使用)
电话 –检查电话。 555999888777(10-15位数字)
zipUS –检查美国邮政编码。 12345-5555(5或9位数字格式)
zipCanada –检查加拿大的邮政编码。 K1A 0B1
creditCard –检查信用卡号。 4111111111111111(13-16位数字)
数字 –检查数字。 0-9
十进制 –检查十进制 100,100.50
字母数字 –检查文本。 a-zA-Z -_。 (通常-所有UTF8符号)
现场演示

结论 (Conclusion)

I hope that today’s article will very useful for your projects. Good luck!

我希望今天的文章对您的项目非常有用。 祝好运!

翻译自: https://www.script-tutorials.com/how-to-make-smoth-jquery-validator-for-forms/

jquery表单验证

 类似资料: