Skip to content Skip to sidebar Skip to footer

How To Put A Tooltip On Input When Its Not Valid

I want to show a tooltip on ma text input when it's not valid This is my function in js: function check() { var ok=true; regLast = /^[a-zA-Z]{2,20}$/; if (!regLast.test(document.

Solution 1:

You should edit the below code accordingly, also link the jquery 1.7 or above-

<script>
 $('#lastName').on('keyup', function () {

$('.text-error').remove();
var ok=true;
regLast = /^[a-zA-Z]{2,20}$/;
if (!regLast.test(document.getElementById("lastName").value))
{
    ok=false;
    $(this).parent('.form-group').append("<span class='text-error'>Please enter a valida string.</span>");
}
return ok;

});
</script>

//CSS add your own CSS for tooltip style etc<styletype="text/css">.form-group{
position:relative;
}
.text-error{
position:absolute;
right:0;
top:0px;
background:red;
color:white;
border-radius:5px;
padding:5px3px;
}
</style>

Hopefully the code will work for you.

Pure Javascript

<!DOCTYPE html><html><head><title></title><styletype="text/css">.form-control{
                position:relative;
                width: 100%;
                float: left;
            }
            .text-error{
                position:absolute;
                right:0;
                top:0px;
                background:red;
                color:white;
                border-radius:5px;
                padding:5px3px;
                display: none;
            }
            .display_block{
                display: block;
            }
            </style></head><body><divclass="form-group"><labelfor ="lastName">Last name:</label><inputtype = "text"class = "form-control"id = "lastName"onkeyup="check()"placeholder = "Put your last name"name = "lastName" /><spanclass="text-error"id="error_lastname"></span></div><scripttype="text/javascript">functioncheck () {
                var div = document.getElementById("error_lastname");
                div.setAttribute('class', 'text-error'); 

                var ok=true;
                regLast = /^[a-zA-Z]{2,20}$/;
                if (!regLast.test(document.getElementById("lastName").value))
                {
                    ok=false;

                    div.setAttribute('class', 'text-error display_block'); 
                    div.innerHTML = "Please enter a valid string.";


                    console.log("XXXX");

                }
                return ok;

            }

            </script></body></html>

Solution 2:

You can add tooltip for the input field like this. Use setAttribute('title', 'some tooltip') to set the tooltip and removeAttribute('title') to remove the tooltip from the input field.

I have added input-event listener to the input field that performs validation of the input value each time you type a character and based on the result of the validation it either adds or removes the tooltip.

If you type just one character and hover over the input field, you should see the tooltip. If you type a second character it disappears (note that you need to move mouse cursor outside of the input field and then back to actually see the tooltip).

functioncheck() {
  var ok = true;
  const regLast = /^[a-zA-Z]{2,20}$/;

  if (!regLast.test(document.getElementById("lastName").value)) {
    ok = false;
  }

  return ok;
}

const inp = document.querySelector('input');
inp.addEventListener('input', event => {
  if (!check(inp.value)) {
    inp.setAttribute('title', 'incorrect value');
  } else {
    inp.removeAttribute('title');
  }
});
<divclass="form-group"><labelfor ="lastName">Last name:</label><inputtype = "text"class = "form-control"id = "lastName"placeholder = "Put your last name"name = "lastName" /></div>

If you need something more sophisticated and more 'visible' then you can use css combined with data attributes. The logic is the same as with the previous code. Based on the result of validation you either add a data attribute to the input field or remove it.

functioncheck() {
  var ok = true;
  const regLast = /^[a-zA-Z]{2,20}$/;

  if (!regLast.test(document.getElementById("lastName").value)) {
    ok = false;
  }

  return ok;
}

const inp = document.querySelector('input');
inp.addEventListener('input', event => {
  if (!check(inp.value)) {
    inp.parentElement.dataset.tip = 'incorrect input value';
  } else {
    delete inp.parentElement.dataset.tip;
  }
});
[data-tip] {
	position:relative;

}
[data-tip]:before {
	content:'';
	display:none;
	content:'';
	border-left: 5px solid transparent;
	border-right: 5px solid transparent;
	border-bottom: 5px solid #1a1a1a;
	position:absolute;
	top:30px;
	left:35px;
	z-index:8;
	font-size:0;
	line-height:0;
	width:0;
	height:0;
}
[data-tip]:after {
	display:none;
	content:attr(data-tip);
	position:absolute;
	top:35px;
	left:0px;
	padding:5px8px;
	background:#1a1a1a;
	color:#fff;
	z-index:9;
	font-size: 0.75em;
	height:18px;
	line-height:18px;
	-webkit-border-radius: 3px;
	-moz-border-radius: 3px;
	border-radius: 3px;
	white-space:nowrap;
	word-wrap:normal;
}
[data-tip]:hover:before,
[data-tip]:hover:after {
	display:block;
}
<divclass="form-group" ><labelfor ="lastName">Last name:</label><inputtype = "text"class = "form-control"id = "lastName"placeholder = "Put your last name"name = "lastName" /></div>

To add the tooltip on form submit instead of hover, you can use submit-event listener and execute the same code as before but you need to add event.preventDefault(); as well to prevent the form from submitting if the validation fails (and you need to change the css slightly).

When you click submit button now, you should see the tooltip if the input value is incorrect.

functioncheck() {
  var ok = true;
  const regLast = /^[a-zA-Z]{2,20}$/;

  if (!regLast.test(document.getElementById("lastName").value)) {
    ok = false;
  }

  return ok;
}

const inp = document.querySelector('input');
const form = document.querySelector('form');

form.addEventListener('submit', event => {
  if (!check(inp.value)) {
    event.preventDefault();
    inp.parentElement.dataset.tip = 'incorrect input value';
  } else {
    delete inp.parentElement.dataset.tip;
  }
});
[data-tip] {
	position:relative;

}
[data-tip]:before {
	content:'';
	border-left: 5px solid transparent;
	border-right: 5px solid transparent;
	border-bottom: 5px solid #1a1a1a;
	position:absolute;
	top:30px;
	left:35px;
	z-index:8;
	font-size:0;
	line-height:0;
	width:0;
	height:0;
}
[data-tip]:after {
	content:attr(data-tip);
	position:absolute;
	top:35px;
	left:0px;
	padding:5px8px;
	background:#1a1a1a;
	color:#fff;
	z-index:9;
	font-size: 0.75em;
	height:18px;
	line-height:18px;
	-webkit-border-radius: 3px;
	-moz-border-radius: 3px;
	border-radius: 3px;
	white-space:nowrap;
	word-wrap:normal;
}
[data-tip]:hover:before,
[data-tip]:hover:after {
	display:block;
}
<form><divclass="form-group" ><labelfor ="lastName">Last name:</label><inputtype = "text"class = "form-control"id = "lastName"placeholder = "Put your last name"name = "lastName" /></div><inputtype="submit"value="submit" /></form>

Solution 3:

You can simply use the HTML5 Form Validation (If you don't want a custom tooltip).

See the code snippet below:

<form><p><labelfor="firstName">First name: </label><inputtype="text"id="firstName"placeholder="Put your first name"pattern="[a-zA-Z]{2,20}"required /></p><p><labelfor="lastName">Last name: </label><inputtype="text"id="lastName"placeholder="Put your last name"pattern="[a-zA-Z]{2,20}"required /></p><inputtype="submit"Value="Submit" /></form>

Also you can use setCustomValidity function when oninvalid event occurs to to change the default message of the required field.

Example:

<form><p><labelfor="firstName">First name: </label><inputtype="text"id="firstName"placeholder="Put your first name"pattern="[a-zA-Z]{2,20}"oninvalid="this.setCustomValidity('Please enter a valid Name')"required /></p><p><labelfor="lastName">Last name: </label><inputtype="text"id="lastName"placeholder="Put your last name"pattern="[a-zA-Z]{2,20}"required /></p><inputtype="submit"Value="Submit" /></form>

Post a Comment for "How To Put A Tooltip On Input When Its Not Valid"