javascript表单验证不是检查号码字段

时间:2013-10-18 12:39:23

标签: javascript forms validation

我正在使用模板,并且内置了一个联系表单,但我必须插入一个联系人号码。字段,所以我添加了一个类型编号的输入字段。现在在JavaScript中我有以下代码,

(function() {

    var $form = $('#contact-form, #comment-form');

    if ($form.length) {
        var $loader = $('<img>', {src: 'images/icons/ajax-loader.gif', width: '16', height: '11', alt: 'Loading...'})
                    .appendTo('#submit-button', $form).hide(),
            $messageBox = $('<div class="message-box short">').appendTo($form).hide(),
            success_msg,
            error_msg1,
            error_msg2;

        // Success and error notification messages for contact form
        if ($form.attr('id') == 'contact-form') {
            success_msg = 'Your message has been sent. Thank you!';
            error_msg1 = 'There was an error sending the email! Please try again later.';
            error_msg2 = 'Sorry, unexpected error. Please try again later.';
        }

        // Success and error notification messages for comment form
        if ($form.attr('id') == 'comment-form') {
            success_msg = 'Your comment has been sent and is awaiting moderation. Thank you!';
            error_msg1 = 'There was an error sending the comment! Please try again later.';
            error_msg2 = 'Sorry, unexpected error. Please try again later.';
        }

        $form.on('click', 'input[type="submit"]', function(e) {
            e.preventDefault();
            var hasError = false;

            // reset error notifications, hide loader and message box
            $form.find('input, textarea, select').removeClass('error').siblings('label').find('span').removeClass('error');
            $loader.hide();
            $messageBox.hide();

            $form.find('input[type="text"], input[type="email"], input[type="checkbox"], input[type="number"], textarea, select').each(function() {
                var $this = $(this),
                    fieldValue = $.trim($this.val());

                if ($this.attr('required')) {

                    // check if the checkbox is checked
                    if ($this.attr('type') == 'checkbox' && $this.is(':checked') == false) {
                        $this.next('label').find('span').addClass('error');
                        hasError = true;
                    }

                    // check if the field has an empty value
                    else if (fieldValue == '' || fieldValue.length < 2) {
                        $this.addClass('error').prev('label').find('span').addClass('error');
                        hasError = true;
                    }
                }

                // email address validation
                if ($this.attr('type') == 'email' && fieldValue.length > 0) {
                    // regex - http://fightingforalostcause.net/misc/2006/compare-email-regex.php
                    var regex=/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i;
                    if (!regex.test(fieldValue)) {
                        $this.addClass('error').prev('label');
                        hasError = true;
                    }
                }

                if ($this.attr('type') == 'number' && fieldValue.length > 0) {
                    // regex - http://fightingforalostcause.net/misc/2006/compare-email-regex.php
                    var regex=/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/;
                    if (!regex.test(fieldValue)) {
                        $this.addClass('error').prev('label');
                        hasError = true;
                    }
                }

            });


            // AJAX request 
            if (!hasError) {
                var localDate = new Date(),
                    localTimezoneOffset = localDate.getTimezoneOffset(), // in minutes
                    form_data = $form.serialize() + '&timezone_offset=' + localTimezoneOffset;

                if ($form.attr('id') == 'comment-form') { // for comment form only
                    var postTitle = $('.blog .single-post .post-content').find('h3, .title').text(),
                        postDay = $('.blog .single-post .post-date').find('.day').text(),
                        postMonth = $('.blog .single-post .post-date').find('.month').text(),
                        postYear = $('.blog .single-post .post-date').find('.year').text(),
                        postDate = postDay + ' ' + postMonth + ' ' + postYear;
                    form_data += '&post_title=' + postTitle + '&post_date=' + postDate;
                }

                $loader.show();

                var request = $.post($form.attr('action'), form_data, function(data) {
                    $loader.hide();
                    if (data.indexOf('success') !== -1) {
                        showMessageBox(success_msg, 'success');
                        $form.find('input[type="text"], input[type="email"], input[type="number"], textarea, select').val('').end()
                            .find('input[type="checkbox"]').attr('checked', false);
                    } else if (data.indexOf('error') !== -1) {
                        showMessageBox(error_msg1, 'error');
                    } else {
                        showMessageBox(error_msg2, 'error');
                    }
                })
                .fail(function() {
                    $loader.hide();
                    showMessageBox(error_msg2, 'error');
                });
            }

            return false; // IE9 hack

        });

    }

    function showMessageBox(msg, type) {
        $messageBox.html('<p>'+msg+'</p>').removeClass('success error').addClass(type).show();

        // scroll to the bottom of the form to show a notification message
        var bottomDiff = $form.offset().top + $form.outerHeight() - $(window).height();
        if ($(document).scrollTop() < bottomDiff) {
            $('html, body').animate({ scrollTop: bottomDiff});
        }
    }

})();

});

在原始脚本中,仅包含文本和电子邮件验证,但我在此处的答案中包含了数字验证。但它仍然不验证联系号码字段,但它确实验证了姓名和电子邮件字段。

0 个答案:

没有答案