JavaScript ÑéÖ¤ API
Ô¼ÊøÑéÖ¤ DOM ·½·¨
ÊôÐÔ | ÃèÊö |
---|---|
checkValidity() | ·µ»Ø true£¬Èç¹û input ÔªËØ°üº¬ÓÐЧÊý¾Ý |
setCustomValidity() | ÉèÖà input ÔªËØµÄ validationMessage ÊôÐÔ¡£ |
checkValidity() ·½·¨
Èç¹ûÊäÈë×ֶΰüº¬ÎÞЧµÄÊý¾Ý£¬ÏÔʾһÌõÏûÏ¢£º
<input id="id1" type="number" min="100" max="300" required> <button onclick="myFunction()">OK</button> <p id="demo"></p> <script> function myFunction() { var inpObj = document.getElementById("id1"); if (inpObj.checkValidity() == false) { document.getElementById("demo").innerHTML = inpObj.validationMessage; } } </script>
Ô¼ÊøÑéÖ¤ DOM ÊôÐÔ
ÊôÐÔ | ÃèÊö |
---|---|
validity | °üº¬Óë input ÔªËØµÄºÏ·¨ÐÔÏà¹ØµÄ²¼¶ûÊôÐÔ¡£ |
validationMessage | °üº¬µ± validity Ϊ false ʱä¯ÀÀÆ÷ÏÔʾµÄÏûÏ¢¡£ |
willValidate | ָʾÊÇ·ñÑéÖ¤ input ÔªËØ¡£ |
ºÏ·¨ÐÔÊôÐÔ
input ÔªËØµÄ validity ÊôÐÔ°üº¬ÁËÓëÊý¾ÝºÏ·¨ÐÔÏà¹ØµÄһϵÁÐÊôÐÔ£º
ÊôÐÔ | ÃèÊö |
---|---|
customError | ÉèÖÃΪ true£¬Èç¹ûÉèÖÃ×Ô¶¨ÒåµÄºÏ·¨ÐÔÏûÏ¢¡£ |
patternMismatch | ÉèÖÃΪ true£¬Èç¹ûÔªËØÖµ²»Æ¥ÅäÆä pattern ÊôÐÔ¡£ |
rangeOverflow | ÉèÖÃΪ true£¬Èç¹ûÔªËØÖµ´óÔ¼Æä max ÊôÐÔ¡£ |
rangeUnderflow | ÉèÖÃΪ true£¬Èç¹ûÔªËØÖµÐ¡ÓÚÆä min ÊôÐÔ¡£ |
stepMismatch | µ±×Ö¶ÎÓµÓÐ step ÊôÐÔ£¬ÇÒÊäÈëµÄ value Öµ²»·ûºÏÉ趨µÄ¼ä¸ôֵʱ£¬¸ÃÊôÐÔֵΪ true¡£ |
tooLong | ÉèÖÃΪ true£¬Èç¹ûÔªËØÖµ³¬¹ýÁËÆä maxLength ÊôÐÔ¡£ |
typeMismatch | µ±×Ö¶ÎµÄ type ÊÇ email »òÕß url µ«ÊäÈëµÄÖµ²»ÊÇÕýÈ·µÄÀàÐÍʱ£¬ÊôÐÔֵΪ true¡£ |
valueMissing | ÉèÖÃΪ true£¬Èç¹ûÔªËØ£¨°üº¬ required£©Ã»ÓÐÖµ¡£ |
valid | ÉèÖÃΪ true£¬Èç¹ûÔªËØÖµÊÇÓÐЧµÄ¡£ |
ʵÀý
Èç¹ûÊäÈë×Ö¶ÎÖеÄÊý×Ö´óÓÚ 100£¨input ÔªËØµÄ max ÊôÐÔ£©£¬ÔòÏÔʾһÌõÏûÏ¢£º
rangeOverflow ÊôÐÔ
<input id="id1" type="number" max="100"> <button onclick="myFunction()">OK</button> <p id="demo"></p> <script> function myFunction() { var txt = ""; if (document.getElementById("id1").validity.rangeOverflow) { txt = "ֵ̫´ó"; } document.getElementById("demo").innerHTML = txt; } </script>
Èç¹ûÊäÈë×Ö¶ÎÖеÄÊý×ÖСÓÚ 100£¨input ÔªËØµÄ min ÊôÐÔ£©£¬ÔòÏÔʾһÌõÏûÏ¢£º
rangeUnderflow ÊôÐÔ
<input id="id1" type="number" min="100"> <button onclick="myFunction()">OK</button> <p id="demo"></p> <script> function myFunction() { var txt = ""; if (document.getElementById("id1").validity.rangeUnderflow) { txt = "ֵ̫С"; } document.getElementById("demo").innerHTML = txt; } </script>