A-A+
基于jQuery验证表单用户名密码实现程序
本文章是基于jQuery验证表单用户名密码效果,有需要的朋友可参考一下。
要求:
(1) 星号为必填项目,要求:用户名6-18个字符;邮箱符合邮箱格式串。用户名不小于6位,邮箱地址要正确的格式。
(2) 在输入框输入信息即时提示录入的要求信息,当不符合要求时即时显示错误信息。
(3) 验证通过后用alert显示结果。
css代码:
- <style type="text/css">
- body
- {
- font-size: 12px;
- }
- form div
- {
- margin: 5px 0;
- }
- .intlabel
- {
- float: left;
- width: 100px;
- text-align: rightright;
- }
- .intinput
- {
- border: 1px solid;
- }
- .sub
- {
- padding-left: 100px;
- }
- .sub input
- {
- margin-right: 10px;
- }
- .formtips
- {
- width: 200px;
- margin: 2px;
- padding: 2px;
- }
- .onError
- {
- background: #FFE0E9 url(../img/NO.gif) no-repeat;
- padding-left: 25px;
- }
- .onSuccess
- {
- background: #E9FBEB url(../img/OK.gif) no-repeat;
- padding-left: 25px;
- }
- .high
- {
- color: red;
- }
- </style>
表单,代码如下:
- <form method="post" action="">
- <div class="int">
- <label>
- 用户名 :</label>
- <input type="text" id="username" class="required" />
- </div>
- <div class="int">
- <label>
- 邮 箱 :</label>
- <input type="text" id="email" class="required" />
- </div>
- <div class="sub">
- <input type="submit" value=" 提交 " id="send" />
- <input type="reset" id="res" />
- </div>
- </form>
jQuery代码如下:
- <script type="text/javascript">
- $(document).ready(function() {
- $(":input.required").each(function() {
- var $required = $("<strong class='high'> *</strong>");
- $(this).parent().append($required);
- });
- $(':input').blur(function() {
- var $parent = $(this).parent();
- $parent.find(".formtips").remove();
- if ($(this).is('#username')) {
- if (this.value == "" || this.value.length < 6) {
- var errorMsg = ' 请输入至少 6 位的用户名 .';
- $parent.append('<span class="formtips onError">' + errorMsg + '</span>');
- }
- else {
- var okMsg = ' 输入正确 .'; $parent.append('<span class="formtips onSuccess">' + okMsg + '</span>');
- }
- };
- if ($(this).is('#email')) {
- if (this.value == "" || (this.value != "" && !/.+@.+.[a-zA-Z]{2,4}$/.test(this.value))) {
- var errorMsg = ' 请输入正确的 E-Mail 地址 .';
- $parent.append('<span class="formtips onError">' + errorMsg + '</span>');
- }
- else { var okMsg = ' 输入正确 .'; $parent.append('<span class="formtips onSuccess">' + okMsg + '</span>'); }
- }
- });
- $(':input').keyup(function() { $(this).triggerHandler("blur"); });
- $(':input').focus(function(){ $(this).triggerHandler("blur"); });
- $('#send').click(function() {
- $(":input.required").trigger('blur'); var numError = $('form .onError').length;
- if (numError > 0) {
- alert("请按要求填写表单");
- return false;
- } alert(" 注册成功 , 密码已发到你的邮箱 , 请查收 .");
- });
- $('#res').click(function() { $(".formtips").remove(); });
- });
- </script>