2017-01-07 35 views
2

我写了一些jQuery来验证我的Bootstrap表单,但是我遇到了一些问题。Bootstrap jQuery - 空字段验证问题

首先,如果用户在不输入任何内容的情况下单击输入字段,我想要一个红色轮廓出现:JSFiddle example here。在这个例子中,我使用Bootstrap Validator plugin,但是我想在不使用插件的情况下模仿这种效果。

其次,与我刚刚提到的问题有关,绿色大纲只有在用户点击提交按钮后才会出现,因此用户在重定向之前只能看到它半秒左右,这使得它有点毫无意义。再次,这可以通过用户点击输入后出现错误/成功轮廓来解决。如果有人能帮助我,将不胜感激。

这是我的代码至今:

HTML:

<form id="auth_form" action="action.php" method="post"> 

    <div class="form-group has-feedback" name="auth_code" id="auth_code"> 
    <label for="auth_code" class="control-label"> 
    Authorisation Code</label> 
    <input class="form-control" id="auth_code_input" name="auth_code_input" type="password"> 
    <span class="form-control-feedback glyphicon" id="iconBad"></span> 
    </div> 

    <div class="form-group"> 
    <div> 
     <button class="btn btn-info" name="submit" type="submit" id="submit">Submit</button> 
    </div> 
    </div> 

</form> 

的jQuery:

$(document).ready(function() { 

    $('#auth_form').on('submit', function(e) { 
    var auth_code = $('#auth_code_input').val() 

    if (auth_code=="") { 
     $('#auth_code').addClass('has-error'); 
     $('#iconBad').removeClass('glyphicon-ok').addClass('glyphicon-remove'); 
     e.preventDefault(); 
    } else { 
     $('#auth_code').removeClass('has-error').addClass('has-success'); 
     $('#iconBad').removeClass('glyphicon-remove').addClass('glyphicon-ok'); 
    } 
    }) 
}) 

JSFiddle

回答

1

试试这个更新小提琴:jsfiddle.net/xqwsobmo/20/

需要添加输入模糊事件和验证输入

$(document).ready(function() {  
    $('#auth_code_input').blur(function(){ 
     if(!ValidateInput()){ 
      e.preventDefault(); 
     } 
    }); 

    $('#auth_form').on('submit', function(e) { 
    if(!ValidateInput()){ 
      e.preventDefault(); 
     } 
    }) 
}); 

function ValidateInput(){ 
    var IsValid=false; 
    var auth_code = $('#auth_code_input').val()  
    if (auth_code=="") { 
     $('#auth_code').addClass('has-error'); 
     $('#iconBad').removeClass('glyphicon-ok').addClass('glyphicon-remove'); 
     IsValid=false; 
    } else { 
     $('#auth_code').removeClass('has-error').addClass('has-success'); 
     $('#iconBad').removeClass('glyphicon-remove').addClass('glyphicon-ok'); 
     IsValid=true; 
    }   
    return IsValid; 
} 
+1

完美,谢谢。 – sinesine

+0

您的欢迎:) –

+1

由于某些最佳原因,您可以使用一个简单的函数来将以下答案分解并在事件'submit'和'blur'中调用它,以便如果有任何更改,您希望这样做将会完成一次你不应该重复它 – PacMan