输入获得焦点时隐藏验证错误

时间:2013-01-11 15:39:07

标签: javascript jquery

这是代码:          - 这里我已经宣布了我的变量:

    var first = $('#first');
    var firstError = $('#firsterror'); // the errors are in span tags (if it matters)
    // and so on... 
    first.blur(validateFirst);
    last.blur(validateLast);
    username.blur(validateUsername);
    password.blur(validatePassword);
    confpassword.blur(validateConfpassword);
    month.blur(validateMonth);
    day.blur(validateDay);
    year.blur(validateYear);
    gender.blur(validateGender);

    $('#myForm').submit(function(){
   if( validateFirst() & validateLast() & validateUsername() & validatePassword() &     validateConfpassword() & validateMonth() & validateDay() & validateYear() &   validateGender() ){
        return true;
      }else{
        return false;
      }
    });

    function validateFirst(){
      if(first.val().length < 5){
        first.addClass('error_input');
        firstError.text('You left this empty!');
        firstError.addClass('error');
        return false;
      }else{
        first.removeClass('error_input');
        firstError.text('');
        return true;
      }
    };
      // and so on...  I would like the code to work as so: When an input recives focus the error should hide else the code should run exactly as it is.
谢谢..

3 个答案:

答案 0 :(得分:1)

我认为你应该使用jQuery validate lib来验证你的表单这里是jQuery验证的cdn链接..

<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>

请注意,您必须在该行之前包含jQuery lib

您只需编写几行代码,如下所示

$('#form_id').validate({
    rules : {
        'el_name' : 'validation_rule'  // like, required
    },
    messages : {
        'el_name' : 'Your error message'
    }
});

答案 1 :(得分:0)

你有没有试过这样的东西?

function removeError() {
     $(this).removeClass('error_input');
     $("#error"+$(this).attr("id")).text("").removeClass("error");
}

first.focus(removeError);
last.blur(removeError);
username.blur(removeError);
....

答案 2 :(得分:0)

试试这个

$('.error_input').focus(function(){
    $(this).removeClass('.error_input');
});