Minimum character count text box

101 views Asked by At

my code isn't working for some reason..here it is:

html:

<input type="text" name="post" maxlength="140" />

and for javascript:

var inpt = document.getElementsByName("post")[0];
// var inputValue=document.getElementById(post).value;
if (inpt.value < 10) {
    return false;
    alert("Post must be longer than 10 characters.");
} else {
return true;
}

i tried it with and without quoting the second line and both do nothing. also i made sure to change inpt.value to inputValue.length when i unquoted the second line.

2

There are 2 answers

0
Arun P Johny On BEST ANSWER

There are 2 problems

var inpt = document.getElementsByName("post")[0];

//need to test the length
if (inpt.value.length < 10) {
    alert("Post must be longer than 10 characters.");
    //return after the alert
    return false;
} else {
    return true;
}

Also make sure that the script is triggered on an event

function validate() {
  var inpt = document.getElementsByName("post")[0];

  //need to test the length
  if (inpt.value.length < 10) {
    alert("Post must be longer than 10 characters.");
    //return after the alert
    return false;
  } else {
    return true;
  }
}
<form onsubmit="return validate()">
  <input type="text" name="post" maxlength="140" />
  <button>Save</button>
</form>

0
James McDowell On

Put the alert before the return statement.