Javascript 检查输入值长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12164751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:17:03  来源:igfitidea点击:

Check input value length

javascriptvalidationinput

提问by user1609394

I have a problem with input checking. I don't want to send the request if the input length is less than 3.

我有输入检查问题。如果输入长度小于 3,我不想发送请求。

My form:

我的表格:

<form method='post' action=''>
    Albūma nosaukums: # # this is the input --><input id='titleeee' type='text' name'album_title' /><br />

    Bilde Nr 1: <input type='file' name='pic_nr1' /><br />
    Bilde Nr 2: <input type='file' name='pic_nr2' /><br />
    Bilde Nr 3: <input type='file' name='pic_nr2' /><br />

    Aktīvs*: 
    <select>
        <option>Jā</option>
        <option>Nē</option>
    </select>

    <br />

    <input Onclick='testlenght(document.getElementById("titleeee"), "Tavs albūma nosaukums ir pa īsu!", "3")' type='submit' value='Pievienot' />
</form>

回答by dm03514

You can add a form onsubmit handler, something like:

您可以添加表单提交处理程序,例如:

<form onsubmit="return validate();">

</form>


<script>function validate() {
 // check if input is bigger than 3
 var value = document.getElementById('titleeee').value;
 if (value.length < 3) {
   return false; // keep form from submitting
 }

 // else form is good let it submit, of course you will 
 // probably want to alert the user WHAT went wrong.

 return true;
}</script>

回答by ogelacinyc

<input type='text' minlength=3 /><br />

<input type='text' minlength=3 /><br />

if browser supports html5,

如果浏览器支持 html5,

it will automatical be validate attributes(minlength) in tag

它将自动验证标签中的属性(最小长度)

but Safari(iOS) doesn't working

但 Safari(iOS) 不起作用