Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum number of characters in search field

I have search field and it doesn't have that typical submit button. It looks like this: enter image description here

HTML:

<div class="input-group">
    <input type="text" class="form-control" name="keyword" id="searchbox" onkeypress="return checkLength()"/>
    <span class="btn btn-primary input-group-addon" onclick="checkLength()"><i class="fa fa-search"></i></span>
</div> 

I only added a span and not the input element for submit button. How do I validate if the user types or inputs not less than 2 characters? If the user types in 1 character only then presses that search button or just hit the enter key, there should be a red error message at the bottom of the search field saying "Keyword should be not less than 2 characters" or something like that.

I tried this code but it's not working:

function checkLength(){
    var textbox = document.getElementById("searchbox");
    if(textbox.value.length <= 10 && textbox.value.length >= 2){
        alert("success");
    } else {
        alert("Keyword should be not less than 2 characters");
        $(document).keypress(function (e) {
            var keyCode = (window.event) ? e.which : e.keyCode;
            if (keyCode && keyCode == 13) {
                e.preventDefault();
                return false;
            }
        });
    }
}

Need help. Thanks.

EDIT:

After inputting keywords and hit the enter key, the page would redirect to a search results page, but that should be prevented from happening if the inputted keyword does not have 2 or more characters, hence, displaying a red text error message below the search field. How to do it?

like image 822
Ethelene Laverne Avatar asked Jan 08 '23 09:01

Ethelene Laverne


1 Answers

You can use pattern attribute in HTML5 input, and you can validate the text with just CSS:

.error {
  display: none;
  font: italic medium sans-serif;
  color: red;
}
input[pattern]:required:invalid ~ .error {
  display: block;
}
<form>
  <input type="text" name="pattern-input" pattern=".{2,}" title="Min 2 characters" required>
  <input type="submit">
  <span class="error">Enter at least two characters</span>
</form>

Here is the Fiddle

Note: This would work with all modern browsers, IE9 and earlier doesn't seems to have support for :invalid, :valid, and :required CSS pseudo-classes till now and Safari have only partial support.

like image 200
nim007 Avatar answered Jan 09 '23 23:01

nim007