返回顶部下载帮助
网站模板
模板颜色分类:
当前位置: html教程 >

javascript验证表单

2020-05-07 文章标签: 表单 浏览次数:

我们讲解下表单的使用,我们先讲解原生的javascript表单验证的写法,然后介绍使用插件验证表达。都可以解决我们问题,只是一个有一定的代码基础,还有种懂点js语法也可以修改达到表单验证。

HTML5教程

为什么要验证表单呢

验证表单

看到这个表单有的网友就会乱写,比如姓名不填,或者很长,很短,或者英文姓名。在填写邮箱的时候格式不正确。只有通过填写正确才可以操作下一步,那么这用到哪些知道点呢,差不多有鼠标离开事件mouseover,检测字符串的长度,js设置css属性等正则表达式几个知识点综合使用。

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" >
$(function() {
$('fieldset').each(function(index) {
var heading = $('legend', this).remove().text();
$('<h3></h3>')
.text(heading)
.prependTo(this);
});
var requiredFlag = ' * ';
var requiredKey = $('input.required:first').next('span').text();
requiredKey = requiredFlag + requiredKey.replace(/^\((.+)\)$/,"$1");
var conditionalFlag = ' ** ';
var conditionalKey = $('input.conditional:first').next('span').text();
conditionalKey = conditionalFlag + conditionalKey.replace(/\((.+)\)/,"$1");
$('form :input').filter('.required')
.next('span').text(requiredFlag).end()
.prev('label').addClass('req-label');
$('form :input').filter('.conditional')
.next('span').text(conditionalFlag);
    //添加注释信息
    $('<p></p>')
    .addClass('field-keys')
    .append(requiredKey + '<br />')
    .append(conditionalKey)
    .insertBefore('#contact');   
  $('input.conditional').hide().each(function() {
    var $thisInput = $(this);
    var $thisFlag = $thisInput.next('span').hide();
    $thisInput.prev('label').find(':checkbox').click(function() {
      if (this.checked) {
        $thisInput.show().addClass('required');
        $thisFlag.show();
        $(this).parent('label').addClass('req-label');
      } else {
        $thisInput.hide().removeClass('required').blur();
        $thisFlag.hide();
        $(this).parent('label').removeClass('req-label');
      };
    });
  });
   $('form :input').blur(function() {
    $(this).parents('li:first').removeClass('warning')
    .find('span.error-message').remove();
    if ($(this).is('.required')) {
      var $listItem = $(this).parents('li:first');
      if (this.value == '') {
        var errorMessage = '必须填写';
        if ($(this).is('.conditional')) {
          errorMessage = '当勾选了前面复选框后,' + errorMessage;
        };
        $('<span></span>')
          .addClass('error-message')
          .text(errorMessage)
          .appendTo($listItem);
        $listItem.addClass('warning');
      };
    };
  }); 
})
</script>
<style type="text/css">
.req-label { font-weight: bold; }
h3 {
    background: #3CF;
    margin: 0;
    padding: 0.3em 0.5em;
}
ul, ol {
    list-style-type: none;
    padding: 0.5em;
    margin: 0;
}
ul { margin-left: 1.5em; }
li { margin: 4px; }
#contact { position: relative; }
p {
    position: absolute;
    right: 1em;
    top: 2em;
    background: #CFC;
    padding: 1em;
}
.error-message { color: red; }
</style>
<title></title>
</head>
<body>
<form id="contact" action="index.html" method="get">
    <fieldset>
        <legend>个人信息</legend>
        <ol>
            <li>
                <label for="name">姓名</label>
                <input class="required" type="text" name="name" id="name">
                <span>(必填)</span></li>
            <li>
                <label for="email">邮箱</label>
                <input class="required" type="text" name="email" id="email">
                <span>(必填)</span></li>
            <li>如何保持联系? (至少选择一种)
                <ul>
                    <li>
                        <label>
                            <input type="checkbox" name="by-contact-type" value="Email" id="by-email">
                            Email</label>
                        <input class="conditional" type="text" name="email" id="email">
                        <span>(当勾选前面复选框后,则必须填写)</span></li>
                    <li>
                        <label>
                            <input type="checkbox" name="by-contact-type" value="Phone" id="by-phone">
                            电话</label>
                        <input class="conditional" type="text" name="phone" id="phone">
                        <span>(当勾选前面复选框后,则必须填写)</span></li>
                    <li>
                        <label>
                            <input type="checkbox" name="by-contact-type" value="QQ" id="by-qq">
                            QQ</label>
                        <input class="conditional" type="text" name="qq" id="qq">
                        <span>(当勾选前面复选框后,则必须填写)</span></li>
                </ul>
            </li>
        </ol>
    </fieldset>
</form>
</body>
</html>

demo2

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" >
$(function() {
$('fieldset').each(function(index) {
var heading = $('legend', this).remove().text();
$('<h3></h3>')
.text(heading)
.prependTo(this);
});
var requiredFlag = ' * ';
var requiredKey = $('input.required:first').next('span').text();
requiredKey = requiredFlag + requiredKey.replace(/^\((.+)\)$/,"$1");
var conditionalFlag = ' ** ';
var conditionalKey = $('input.conditional:first').next('span').text();
conditionalKey = conditionalFlag + conditionalKey.replace(/\((.+)\)/,"$1");
$('form :input').filter('.required')
.next('span').text(requiredFlag).end()
.prev('label').addClass('req-label');
$('form :input').filter('.conditional')
.next('span').text(conditionalFlag);
    //添加注释信息
    $('<p></p>')
    .addClass('field-keys')
    .append(requiredKey + '<br />')
    .append(conditionalKey)
    .insertBefore('#contact');   
  $('input.conditional').hide().each(function() {
    var $thisInput = $(this);
    var $thisFlag = $thisInput.next('span').hide();
    $thisInput.prev('label').find(':checkbox').click(function() {
      if (this.checked) {
        $thisInput.show().addClass('required');
        $thisFlag.show();
        $(this).parent('label').addClass('req-label');
      } else {
        $thisInput.hide().removeClass('required').blur();
        $thisFlag.hide();
        $(this).parent('label').removeClass('req-label');
      };
    });
  });
   $('form :input').blur(function() {
    $(this).parents('li:first').removeClass('warning')
    .find('span.error-message').remove();
    if ($(this).is('.required')) {
      var $listItem = $(this).parents('li:first');
      if (this.value == '') {
        var errorMessage = '必须填写';
        if ($(this).is('.conditional')) {
          errorMessage = '当勾选了前面复选框后,' + errorMessage;
        };
        $('<span></span>')
          .addClass('error-message')
          .text(errorMessage)
          .appendTo($listItem);
        $listItem.addClass('warning');
      };
    };
    if ($(this).is('#email')) {
      var $listItem = $(this).parents('li:first');
      if (this.value != '' && !/.+@.+\.[a-zA-Z]{2,4}$/.test(this.value)) {
        var errorMessage = '电子邮件格式不正确';
        $('<span></span>')
          .addClass('error-message')
          .text(errorMessage)
          .appendTo($listItem);
        $listItem.addClass('warning');
      };
    };
  }); 
})
</script>
<style type="text/css">
.req-label { font-weight: bold; }
h3 {
    background: #3CF;
    margin: 0;
    padding: 0.3em 0.5em;
}
ul, ol {
    list-style-type: none;
    padding: 0.5em;
    margin: 0;
}
ul { margin-left: 1.5em; }
li { margin: 4px; }
#contact { position: relative; }
p {
    position: absolute;
    right: 1em;
    top: 2em;
    background: #CFC;
    padding: 1em;
}
.error-message { color: red; }
</style>
<title></title>
</head>
<body>
<form id="contact" action="index.html" method="get">
    <fieldset>
        <legend>个人信息</legend>
        <ol>
            <li>
                <label for="name">姓名</label>
                <input class="required" type="text" name="name" id="name">
                <span>(必填)</span></li>
            <li>
                <label for="email">邮箱</label>
                <input class="required" type="text" name="email" id="email">
                <span>(必填)</span></li>
            <li>如何保持联系? (至少选择一种)
                <ul>
                    <li>
                        <label>
                            <input type="checkbox" name="by-contact-type" value="Email" id="by-email">
                            Email</label>
                        <input class="conditional" type="text" name="email" id="email">
                        <span>(当勾选前面复选框后,则必须填写)</span></li>
                    <li>
                        <label>
                            <input type="checkbox" name="by-contact-type" value="Phone" id="by-phone">
                            电话</label>
                        <input class="conditional" type="text" name="phone" id="phone">
                        <span>(当勾选前面复选框后,则必须填写)</span></li>
                    <li>
                        <label>
                            <input type="checkbox" name="by-contact-type" value="QQ" id="by-qq">
                            QQ</label>
                        <input class="conditional" type="text" name="qq" id="qq">
                        <span>(当勾选前面复选框后,则必须填写)</span></li>
                </ul>
            </li>
        </ol>
    </fieldset>
</form>
</body>
</html>

demo3

js验证表单

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" >
$(function() {
$('fieldset').each(function(index) {
var heading = $('legend', this).remove().text();
$('<h3></h3>')
.text(heading)
.prependTo(this);
});
var requiredFlag = ' * ';
var requiredKey = $('input.required:first').next('span').text();
requiredKey = requiredFlag + requiredKey.replace(/^\((.+)\)$/,"$1");
var conditionalFlag = ' ** ';
var conditionalKey = $('input.conditional:first').next('span').text();
conditionalKey = conditionalFlag + conditionalKey.replace(/\((.+)\)/,"$1");
$('form :input').filter('.required')
.next('span').text(requiredFlag).end()
.prev('label').addClass('req-label');
$('form :input').filter('.conditional')
.next('span').text(conditionalFlag);
    //添加注释信息
    $('<p></p>')
    .addClass('field-keys')
    .append(requiredKey + '<br />')
    .append(conditionalKey)
    .insertBefore('#contact');   
  $('input.conditional').hide().each(function() {
    var $thisInput = $(this);
    var $thisFlag = $thisInput.next('span').hide();
    $thisInput.prev('label').find(':checkbox').click(function() {
      if (this.checked) {
        $thisInput.show().addClass('required');
        $thisFlag.show();
        $(this).parent('label').addClass('req-label');
      } else {
        $thisInput.hide().removeClass('required').blur();
        $thisFlag.hide();
        $(this).parent('label').removeClass('req-label');
      };
    });
  });
   $('form :input').blur(function() {
    $(this).parents('li:first').removeClass('warning')
    .find('span.error-message').remove();
    if ($(this).is('.required')) {
      var $listItem = $(this).parents('li:first');
      if (this.value == '') {
        var errorMessage = '必须填写';
        if ($(this).is('.conditional')) {
          errorMessage = '当勾选了前面复选框后,' + errorMessage;
        };
        $('<span></span>')
          .addClass('error-message')
          .text(errorMessage)
          .appendTo($listItem);
        $listItem.addClass('warning');
      };
    };
    if ($(this).is('#email')) {
      var $listItem = $(this).parents('li:first');
      if (this.value != '' && !/.+@.+\.[a-zA-Z]{2,4}$/.test(this.value)) {
        var errorMessage = '电子邮件格式不正确';
        $('<span></span>')
          .addClass('error-message')
          .text(errorMessage)
          .appendTo($listItem);
        $listItem.addClass('warning');
      };
    };
  }); 
  $('form').submit(function() {
    $('#submit-message').remove();
    $(':input.required').trigger('blur');
    var numWarnings = $('.warning', this).length;
    if (numWarnings) {
      var fieldList = [];
      $('.warning label').each(function() {
        fieldList.push($(this).text());
      });
      $('<div></div>')
      .attr({
        'id': 'submit-message',
        'class': 'warning'
      })
      .append('请重新填写下面 ' + numWarnings + ' 个字段:<br />')
      .append('&bull; ' + fieldList.join('<br />&bull; '))
      .insertBefore('#send');
      return false;
    };
  });  
})
</script>
<style type="text/css">
.req-label { font-weight: bold; }
h3 {
    background: #3CF;
    margin: 0;
    padding: 0.3em 0.5em;
}
ul, ol {
    list-style-type: none;
    padding: 0.5em;
    margin: 0;
}
ul { margin-left: 1.5em; }
li { margin: 4px; }
#contact { position: relative; }
p {
    position: absolute;
    right: 1em;
    top: 2em;
    background: #CFC;
    padding: 1em;
}
.error-message { color: red; }
.warning { color: #F0F; }
</style>
<title></title>
</head>
<body>
<form id="contact" action="index.html" method="get">
    <fieldset>
        <legend>个人信息</legend>
        <ol>
            <li>
                <label for="name">姓名</label>
                <input class="required" type="text" name="name" id="name">
                <span>(必填)</span></li>
            <li>
                <label for="email">邮箱</label>
                <input class="required" type="text" name="email" id="email">
                <span>(必填)</span></li>
            <li>如何保持联系?
                <ul>
                    <li>
                        <label>
                            <input type="checkbox" name="by-contact-type" value="Email" id="by-email">
                            Email</label>
                        <input class="conditional" type="text" name="email" id="email">
                        <span>(当勾选前面复选框后,则必须填写)</span></li>
                    <li>
                        <label>
                            <input type="checkbox" name="by-contact-type" value="Phone" id="by-phone">
                            电话</label>
                        <input class="conditional" type="text" name="phone" id="phone">
                        <span>(当勾选前面复选框后,则必须填写)</span></li>
                    <li>
                        <label>
                            <input type="checkbox" name="by-contact-type" value="QQ" id="by-qq">
                            QQ</label>
                        <input class="conditional" type="text" name="qq" id="qq">
                        <span>(当勾选前面复选框后,则必须填写)</span></li>
                </ul>
            </li>
            <li>
                <input name="send" id="send" value="提交" type="submit">
            </li>
        </ol>
    </fieldset>
</form>
</body>
</html>


建站咨询 - 联系我们 - 广告服务 - 友情链接 - 版权声明 - 手机版

免责声明:站内所有资源仅供学习与参考,请勿用于商业用途,否则产生的一切后果将由您自己承担!版权归原创者所有,如果侵犯了您的权益,请通知我们,我们会及时删除侵权内容。