简体   繁体   中英

Show HTML5 validation message

I'm using HTML5 Constraint Validation and I'd like to show validation message after each blur.

HTML

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

JS

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

Is it possible to do something similar?

有效按摩

It is possible. Like this:

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

You can manually trigger HTML5 form validation like so:

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

Obviously the above is with jQuery, but you can just as easily adapt for pure 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');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM