Check input value length
Asked Answered
T

3

31

I have a problem with input checking. I don't want to send the request if the input length is less than 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>
Thirtytwomo answered 28/8, 2012 at 17:50 Comment(1)
You've referenced testlenght(), but where is the function?Triiodomethane
B
58

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>
Bluestone answered 28/8, 2012 at 17:52 Comment(4)
Can you please type full skript, i am not smart in javascript ;(Thirtytwomo
that should be the full thingBluestone
I know this post is years old, but to help some beginners (Beginners should have a chance too, since we all began in similar ways.. sooo..) : The part of <form... to </form> should go in your plain html document and that whole function part into a <script> (put it here) </script> tag in that same document, or put it in a separate file called script.js and reference it with <script src='script.js'></script>. That's all. Sorry, if this comment isn't "S.O. compilant", I just want to help some bloody beginners.Cesta
I think the "return" statement is missing: <form onsubmit="return validate();">Llywellyn
Q
6

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

if browser supports html5,

it will automatical be validate attributes(minlength) in tag

but Safari(iOS) doesn't working

Quickstep answered 17/8, 2016 at 5:50 Comment(0)
B
0

There's 3 way's I would do this.

1:

const Element = document.getElementById("Element-ID");
if (Element.value.length >= 3) {
    // Do your code thing!
    console.log("Input length is longer or is 3");
};

2:

<input type="text" minlength=3/>
// I recommend option 1 sense it's more customize able.

3:

const Element = ddocument.getElementById("Element-ID");

switch(Element.value.length) {
    case 3:
    console.log("length is 3");
    break;
    
    default:
    console.log("length is not 3 or is less then 3");
    break;
};
Bothersome answered 16/3, 2024 at 23:17 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.