显示HTML5验证消息

时间:2015-07-22 15:07:20

标签: javascript html dom

我正在使用HTML5约束验证,我想在每次模糊后显示验证消息。

HTML

<input id="texInput" type="text" onblur="validation()" required>

JS

var el = document.getElementById('texInput');
if (!el.checkValidity()) {
    //Here show message
} 

是否可以做类似的事情?

valid-massage

4 个答案:

答案 0 :(得分:0)

有可能。 像这样:

HTML:

<input id="texInput42" type="text" onblur="function(){validation('texInput42');}" required>

JS:

function validation(_id){
    var isValid= false;
    //check validity here:
    var el = document.getElementById(_id);
    if(el.innerHtml == '') isValid=false; 
    if(el.innerHtml.length > 0) isValid=true; 

    if (isValid) {
      //Here show message
      alert('debug: it's ok');
      //or change css to color el in green, e.g.
    }
} 

答案 1 :(得分:0)

您可以手动触发HTML5表单验证,如下所示:

$('input').blur(function(e) {
    e.target.checkValidity();
});

显然上面是jQuery,但你可以很容易地适应纯JS。

答案 2 :(得分:0)

HTML:

<!-- anywhere in your page, at the bottom e.g.->
<div id='myabsdiv' ><span class='icon'> </span> <span class="text">Please ...</span> </div>

JS:

  if (!el.checkValidity()) {
        //Here show message
        //show an absolute div...
        $("#myabsdiv").css('top', el.offset.y+el.height());
        $("#myabsdiv").css('left', el.offset.x - $("#myabsdiv").width()/2);
        $("#myabsdiv").show();
    } 

CSS:

#myabsdiv{
    height:50px;
    width:180px;

    position:absolute;
    display:none;

    background-image:url('make a PNG');
}

答案 3 :(得分:0)

相关问题