Проверка Javascript со значением поля по умолчанию - PullRequest
1 голос
/ 14 марта 2012

новичок здесь. Мне нужна помощь.

Я использую предварительно написанный валидатор формы javascript для моего сайта, но дело в том, что он не предназначен для полей со значением по умолчанию . Таким образом, проблема заключается в том, что валидатор считает значения «Имя» и «Сообщение» действительными, и сообщение проходит без сообщения об ошибке.

Я провел некоторое исследование и увидел некоторые предложения, но, обладая очень небольшими знаниями в javascript, я не знаю, как их реализовать или как создать еще один набор правил проверки.

Кстати, я использую бесплатную контактную форму от [http://www.faridhadi.com/][1]

Ниже приведен скрипт, над которым я работаю:

Надеюсь, вы, ребята, сможете мне помочь! Спасибо!

// JavaScript Document

$(document).ready(function() {

    $('#contactForm #submit').click(function() {
        // Fade in the progress bar
        $('#contactForm #formProgress').hide();
        $('#contactForm #formProgress').html('<img src="images/ajax-loader.gif" /> Sending&hellip;');
        $('#contactForm #formProgress').fadeIn();

        // Disable the submit button
        $('#contactForm #submit').attr("disabled", "disabled");

        // Clear and hide any error messages
        $('#contactForm .formError').html('');

        // Set temaprary variables for the script
        var isFocus=0;
        var isError=0;

        // Get the data from the form
        var name=$('#contactForm #name').val(); 
        var email=$('#contactForm #email').val();
        var subject=$('#contactForm #subject').val();
        var message=$('#contactForm #message').val();

        // Validate the data
        if(name=='') {
            $('#contactForm #errorName').html('This is a required field.');
            $('#contactForm #name').focus();
            isFocus=1;
            isError=1;
        }
        if(email=='') {
            $('#contactForm #errorEmail').html('This is a required field.');
            if(isFocus==0) {
                $('#contactForm #email').focus();
                isFocus=1;
            }
            isError=1;
        } else {
            var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
            if(reg.test(email)==false) {
                $('#contactForm #errorEmail').html('Invalid email address.');
                if(isFocus==0) {
                    $('#contactForm #email').focus();
                    isFocus=1;
                }
                isError=1;
            }
        }
        if(message=='') {
            $('#contactForm #errorMessage').html('This is a required field.');
            if(isFocus==0) {
                $('#contactForm #message').focus();
                isFocus=1;
            }
            isError=1;
        }

        // Terminate the script if an error is found
        if(isError==1) {
            $('#contactForm #formProgress').html('');
            $('#contactForm #formProgress').hide();

            // Activate the submit button
            $('#contactForm #submit').attr("disabled", "");

            return false;
        }

        $.ajaxSetup ({
            cache: false
        });

        var dataString = 'name='+ name + '&email=' + email + '&subject=' + subject + '&message=' + message;  
        $.ajax({
            type: "POST",
            url: "php/submit-form-ajax.php",
            data: dataString,
            success: function(msg) {

                //alert(msg);

                // Check to see if the mail was successfully sent
                if(msg=='Mail sent') {
                    // Update the progress bar
                    $('#contactForm #formProgress').html('<img src="images/ajax-complete.gif" /> Message sent.').delay(2000).fadeOut(400);

                    // Clear the subject field and message textbox
                    $('#contactForm #subject').val('');
                    $('#contactForm #message').val('');
                } else {
                    $('#contactForm #formProgress').html('');
                    alert('There was an error sending your email. Please try again.');
                }

                // Activate the submit button
                $('#contactForm #submit').attr("disabled", "");
            },
            error: function(ob,errStr) {
                $('#contactForm #formProgress').html('');
                alert('There was an error sending your email. Please try again.');

                // Activate the submit button
                $('#contactForm #submit').attr("disabled", "");
            }
        });

        return false;
    });
});

Ответы [ 2 ]

0 голосов
/ 14 марта 2012

Если по умолчанию вы имеете в виду начальную value="No Subject", вы можете изменить присвоение переменных для учета этого значения, если ввод пуст;

var name = $('#contactForm #name');
name = $.trim(name.val()) || name.prop("defaultValue");
...
var email = ....
0 голосов
/ 14 марта 2012

Вам лучше использовать атрибут HTML5 placeholder в качестве значения по умолчанию. Для поддержки всех браузеров вы можете использовать плагин jQuery watermark , который заполняет старый браузер для поддержки placeholder.

Для проверки также лучше использовать широко используемый jQuery Validator плагин

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...