簡體   English   中英

顯示HTML5驗證消息

[英]Show HTML5 validation message

我正在使用HTML5約束驗證,並且希望在每次模糊后顯示驗證消息。

的HTML

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

JS

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

是否可以做類似的事情?

有效按摩

有可能的。 像這樣:

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.
    }
} 

您可以像這樣手動觸發HTML5表單驗證:

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

顯然,以上是使用jQuery的,但是您也可以輕松地適應純JS。

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');
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM