如何在submit和keyup中验证表单?

时间:2022-11-24 10:00:25

My form validates on keyup, but when I try to validate it on submit too I just can't think what to do.

我的表单验证了keyup,但是当我尝试在提交上验证它时,我就是不知道该怎么做。

This is my HTML:

这是我的HTML:

   <form action="#" method="post">                      
        <section class="col">   

            <section class="row">                   
                <label for="name">Name</label>
                <input type="text" name="name" value="" id="name" class="field validate-field valid-name" />                    
            </section>

            <section class="row">                   
                <label for="email">Email Address</label>
                <input type="text" name="email" value="" id="email" class="field validate-field valid-mail" />                  
            </section>

            <section class="row">                   
                <label for="phone">Phone Number</label>
                <input type="text" name="phone" value="" id="phone" class="field validate-field valid-phone" />                     
            </section>                  
        </section>

        <section class="col">               
            <label for="message">Message</label>
            <textarea class="field validate-field valid-text" name="message" id="message-field"></textarea>
            <input type="submit" value="Submit" class="submit-button" />
        </section>
   </form>

JS:

JS:

function validate( field ){
    var value = field.val();
    var to_label = field.parent().find('label');
    var error = false;
    var error_message = '';

    to_label.find('span').remove();

    if ( field.hasClass('validate-field') && value == '' ) {
        error = true;
        error_message = 'Empty Field';  
    } else if ( field.hasClass('valid-name') && valid_name(value) == false ) {
        error = true;
        error_message = 'Name must consist characters only';
    } else if ( field.hasClass('valid-mail') && valid_email(value) == false ) {
        error = true;
        error_message = 'Invalid Email';
    } else if ( field.hasClass('valid-phone') && valid_phone(value) == false ) {
        error = true;
        error_message = 'Your phone must be digits only';
    };

    if ( error == true ) {
        to_label.append('<span>'+ error_message +'</span>');
    }
};


$('.validate-field').live('keyup', function(){
    validate( $(this) );
});

function valid_name(value){
    var valid = /^([a-zA-Z_\.\-\+])+$/;
    return valid.test(value);
};

function valid_email(value){
    var valid = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return valid.test(value);
};

function valid_phone(value){
    var valid = /^[0-9-+]+$/;
    return valid.test(value);

};

};

And I have to add something like this:

我必须加上这样的东西:

$('form').live('submit', function(){

    if ( "...validated..." ) {  
        $.post('send.php', $('form').serialize(), function(){
            alert('sent to PHP.');
        })  
    };
    return false;
});

What should be in the submit function?

提交函数中应该包含什么?

I have tried:

我有尝试:

$('form').live('submit', function(){

    var valid = validate( $('.field') )

    if ( valid  == true ) { 
        $.post('send.php', $('form').serialize(), function(){
            alert('sent to PHP.');
        })  
    };
    return false;
});

But this validates all the forms with all the validation (e-mail, phone ...). I have tried in validation() function to add if (error == false){ return: true }, then in submit function ran validation() and added if ( validation() == true ){ .. to send php ..}. That didn't work too. What I need to do ?

但是,这验证了所有形式的所有验证(电子邮件、电话…)。我在validation()函数中尝试添加if (error == false){return: true},然后在submit函数中运行验证()并添加if (validation() == true){。将php…}。没有工作。我需要做什么?

2 个解决方案

#1


2  

I guess you can validate the whole form by:

我猜你可以通过以下方式来验证整个表格:

function validateAll() {
    var valid = true;
    $('form').find('.validate-field').each(function (i, e) {
        if (!validate($(this))) {
           valid = false;
            return;
        }
    });
    return valid;
}

function validate( field ){
    var value = field.val();
    var to_label = field.parent().find('label');
    var error = false;
    var error_message = '';

    to_label.find('span').remove();

    if ( field.hasClass('validate-field') && value == '' ) {
        error = true;
        error_message = 'Empty Field';  
    } else if ( field.hasClass('valid-name') && valid_name(value) == false ) {
        error = true;
        error_message = 'Name must consist characters only';
    } else if ( field.hasClass('valid-mail') && valid_email(value) == false ) {
        error = true;
        error_message = 'Invalid Email';
    } else if ( field.hasClass('valid-phone') && valid_phone(value) == false ) {
        error = true;
        error_message = 'Your phone must be digits only';
    };

    if (error) {
        to_label.append('<span>'+ error_message +'</span>');
    }
    return !error;

};

$('form').live('submit', function(){

    if (validateAll()) {  
        $.post('send.php', $('form').serialize(), function(){
            alert('sent to PHP.');
        })  
    };
    return false;
});

That's the option which requires the smallest amount of refactoring, on my opinion.

根据我的观点,这是需要最少重构的选项。

Just let me explain you what the function validateAll does. It finds all fields with class validate-field and pass it as argument to the validate function. Because of the refactoring I made in validate it returns false if the field is not valid so when we call validate with specific input and it's invalid we just return false (the form is not valid).

让我来解释一下函数validateAll的作用。它查找所有具有类validate字段的字段,并将其作为参数传递给validate函数。因为我在validate中做了重构,所以如果这个字段无效,所以当我们用特定的输入进行验证时,它会返回false,并且它是无效的,我们返回false(表单无效)。

Here is an example in JSfiddle.

这里有一个JSfiddle的例子。

For more advance validation I can recommend you validation plugins like: http://docs.jquery.com/Plugins/Validation or jqxValidator.

为了获得更多的预先验证,我可以推荐您使用诸如:http://docs.jquery.com/Plugins/Validation或jqxValidator之类的验证插件。

#2


0  

You are almost done. Just add below code, it'll work

你几乎完成了。只需添加下面的代码,就可以了。

$('form').submit(function(){
    var field = $(this).find('.validate-field');
    validate( field );
});

Hope this will solve your issue.

希望这能解决你的问题。

Fiddle: http://jsfiddle.net/r1webs/cFeCx/

小提琴:http://jsfiddle.net/r1webs/cFeCx/

#1


2  

I guess you can validate the whole form by:

我猜你可以通过以下方式来验证整个表格:

function validateAll() {
    var valid = true;
    $('form').find('.validate-field').each(function (i, e) {
        if (!validate($(this))) {
           valid = false;
            return;
        }
    });
    return valid;
}

function validate( field ){
    var value = field.val();
    var to_label = field.parent().find('label');
    var error = false;
    var error_message = '';

    to_label.find('span').remove();

    if ( field.hasClass('validate-field') && value == '' ) {
        error = true;
        error_message = 'Empty Field';  
    } else if ( field.hasClass('valid-name') && valid_name(value) == false ) {
        error = true;
        error_message = 'Name must consist characters only';
    } else if ( field.hasClass('valid-mail') && valid_email(value) == false ) {
        error = true;
        error_message = 'Invalid Email';
    } else if ( field.hasClass('valid-phone') && valid_phone(value) == false ) {
        error = true;
        error_message = 'Your phone must be digits only';
    };

    if (error) {
        to_label.append('<span>'+ error_message +'</span>');
    }
    return !error;

};

$('form').live('submit', function(){

    if (validateAll()) {  
        $.post('send.php', $('form').serialize(), function(){
            alert('sent to PHP.');
        })  
    };
    return false;
});

That's the option which requires the smallest amount of refactoring, on my opinion.

根据我的观点,这是需要最少重构的选项。

Just let me explain you what the function validateAll does. It finds all fields with class validate-field and pass it as argument to the validate function. Because of the refactoring I made in validate it returns false if the field is not valid so when we call validate with specific input and it's invalid we just return false (the form is not valid).

让我来解释一下函数validateAll的作用。它查找所有具有类validate字段的字段,并将其作为参数传递给validate函数。因为我在validate中做了重构,所以如果这个字段无效,所以当我们用特定的输入进行验证时,它会返回false,并且它是无效的,我们返回false(表单无效)。

Here is an example in JSfiddle.

这里有一个JSfiddle的例子。

For more advance validation I can recommend you validation plugins like: http://docs.jquery.com/Plugins/Validation or jqxValidator.

为了获得更多的预先验证,我可以推荐您使用诸如:http://docs.jquery.com/Plugins/Validation或jqxValidator之类的验证插件。

#2


0  

You are almost done. Just add below code, it'll work

你几乎完成了。只需添加下面的代码,就可以了。

$('form').submit(function(){
    var field = $(this).find('.validate-field');
    validate( field );
});

Hope this will solve your issue.

希望这能解决你的问题。

Fiddle: http://jsfiddle.net/r1webs/cFeCx/

小提琴:http://jsfiddle.net/r1webs/cFeCx/