Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check value length with using Javascript?

Tags:

javascript

Hello everyone I would like to ask how to check value's length from textbox ?

Here is my code :

@*<script>
    function validateForm() {
        var x = document.forms["frm"]["txtCardNumber"].value;
        if (x == null || x == "" ) {
            alert("First name must be filled out");
            return false;
        }
    }
</script>*@

When I run my script yeap I got alert message but I'm trying to add property which control the texbox' input length.

like image 735
Teodoris Avatar asked Oct 28 '25 05:10

Teodoris


2 Answers

You could use x.length to get the length of the string:

if (x.length < 5) {
    alert('please enter at least 5 characters');
    return false;
}

Also I would recommend you using the document.getElementById method instead of document.forms["frm"]["txtCardNumber"].

So if you have an input field:

<input type="text" id="txtCardNumber" name="txtCardNumber" />

you could retrieve its value from the id:

var x = document.getElementById['txtCardNumber'].value;
like image 57
Darin Dimitrov Avatar answered Oct 30 '25 23:10

Darin Dimitrov


Still more better script would be:

<input type="text" name="txtCardNumber" id="txtCardNumber" />

And in the script:

if (document.getElementById(txtCardNumber).value.length < 5) {
    alert('please enter at least 5 characters');
    return false;
}
like image 20
Praveen Kumar Purushothaman Avatar answered Oct 30 '25 21:10

Praveen Kumar Purushothaman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!