Search code examples
javascripthtmltextinput

Minimum character count text box


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.


Solution

  • 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>