What is the process for setting up automatic tooltip validation messages?

After creating a sample file for validation, everything seems to be working smoothly...

However, I now have a specific requirement - I would like to make some modifications while validating. The error message should automatically display in a tooltip. This tooltip should appear automatically when there is an error and disappear once the error is resolved. It should remain visible until the error is fixed.

https://i.sstatic.net/xZcey.jpg

If it's possible to achieve this without using jQuery or with the use of jQuery, that works too.

https://i.sstatic.net/JldBn.jpg

var app = angular.module('myapp', ['UserValidation']);

myappCtrl = function($scope) {
    $scope.formAllGood = function () {
        return ($scope.usernameGood && $scope.passwordGood && $scope.passwordCGood)
    }
        
}

angular.module('UserValidation', []).directive('validUsername', function () {
    return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {
            ctrl.$parsers.unshift(function (viewValue) {
                // Any way to read the results of a "required" angular validator here?
                var isBlank = viewValue === ''
                var invalidChars = !isBlank && !/^[A-z0-9]+$/.test(viewValue)
                var invalidLen = !isBlank && !invalidChars && (viewValue.length < 5 || viewValue.length > 20)
                ctrl.$setValidity('isBlank', !isBlank)
                ctrl.$setValidity('invalidChars', !invalidChars)
                ctrl.$setValidity('invalidLen', !invalidLen)
                scope.usernameGood = !isBlank && !invalidChars && !invalidLen

            })
        }
    }
}).directive('validPassword', function () {
    return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {
            ctrl.$parsers.unshift(function (viewValue) {
                var isBlank = viewValue === ''
                var invalidLen = !isBlank && (viewValue.length < 8 || viewValue.length > 20)
                var isWeak = !isBlank && !invalidLen && !/(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z])/.test(viewValue)
                ctrl.$setValidity('isBlank', !isBlank)
                ctrl.$setValidity('isWeak', !isWeak)
                ctrl.$setValidity('invalidLen', !invalidLen)
                scope.passwordGood = !isBlank && !isWeak && !invalidLen

            })
        }
    }
}).directive('validPasswordC', function () {
    return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {
            ctrl.$parsers.unshift(function (viewValue, $scope) {
                var isBlank = viewValue === ''
                var noMatch = viewValue != scope.myform.password.$viewValue
                ctrl.$setValidity('isBlank', !isBlank)
                ctrl.$setValidity('noMatch', !noMatch)
                scope.passwordCGood = !isBlank && !noMatch
            })
        }
    }
})
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap-combined.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
    <form  name="myform" class="form form-horizontal" ng-controller="myappCtrl" novalidate>
    <legend>Angular User Validation with Bootstrap Decorations</legend>
    <div class="control-group" ng-class="{error:!myform.username.$valid}">
        <label for="inputUsername" class="control-label">Username:</label>
        <div class="controls">
            <input type="text" id="inputUsername" name="username" ng-model="username" valid-username />
            <div class="help-inline">
                <span ng-show="!!myform.username.$error.isBlank">Username Required.</span>
<span ng-show="!!myform.username.$error.invalidChars">Username must contain letters &amp; spaces only.</span>
                <span ng-show="!!myform.username.$error.invalidLen">Username must be 5-20 characters.</span>
            </div>
        </div>
    </div>
    <div class="control-group" ng-class="{error:!myform.password.$valid}">
        <label for="inputPassword" class="control-label">Password:</label>
        <div class="controls">
            <input type="text" id="inputPassword" name="password" ng-model="password" valid-password />
            <div class="help-inline">
                <span ng-show="!!myform.password.$error.isBlank">Password Required.</span>
                <span ng-show="!!myform.password.$error.isWeak">Must contain one upper &amp; lower case letter and a non-letter (number or symbol.)</span> 
                <span ng-show="!!myform.password.$error.invalidLen">Must be 8-20 characters.</span>
            </div>
        </div>
    </div>
    <div class="control-group" ng-class="{error:!myform.password_c.$valid}">
        <label for="password_c" class="control-label">Confirm Password:</label>
        <div class="controls">
            <input type="text" id="password_c" name="password_c" ng-model="password_c" valid-password-c />
            <div class="help-inline"> 
                <span ng-show="!!myform.password_c.$error.isBlank">Confirmation Required.</span>
                <span ng-show="!!myform.password_c.$error.noMatch">Passwords don't match.</span>
            </div>
        </div>
    </div>
    <div class="form-actions" ng-show="formAllGood()">
        <input type="submit" class="btn btn-primary" value="Submit" />
    </div>
    </form></div>

Answer №1

Indeed, it is entirely feasible to display or hide a popover based on any event. The code below illustrates a validation function for numbers utilizing a popover.

JSFiddle.

function validate(el) {
  var regex = /^\d+$/g;
  var valid = regex.test(el.value);
  if (!valid) {
    
    // Check if the popover is already visible to manage any flickering effect.
    if ($("#txtInput").next('div.popover').length == 0) {
      
      $('#txtInput').popover({
        placement: 'bottom',
        content: 'This is not a valid entry'
      }).popover('show');
      
    }
  } else {
    $('#txtInput').popover('hide');
  }
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>


<input type="text" id="txtInput" onkeyup="validate(this)">

References:

Answer №2

Top choice is using Parsley.js

Reasons to Choose Parsley :

  • You can customize Validation Event (onsubmit, onkeyup, or any other event)
  • Easily customize Validation Style
  • Validation message disappears automatically when input meets conditions

Take a look at their examples

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am struggling to apply custom CSS styles to the scrollbar within a Card component using MUI react

import React from "react"; import Card from "@mui/material/Card"; import CardActions from "@mui/material/CardActions"; import CardContent from "@mui/material/CardContent"; import CardMedia from "@mui/material/Ca ...

Using @{Controller.action()} in JavaScript files can be a great way to dynamically call

Currently, I am in the process of developing a web application using jQuery. One aspect of this project involves making numerous $.get(..) and $.post(..) action-calls to my Play Controllers. For instance: $.get('@{Patients.activeEpisodes()}', f ...

Alternating the tooltip icon based on the field's condition

Looking for a way to create a tooltip for an input field that involves changing icons based on certain conditions. An example scenario is the password field in a registration form. Seeking advice on the best approach to achieve this. Currently, here' ...

The size of the table and the ability to scroll cannot be adjusted

<div id="answer3" class="tab-pane"> <div class="col-md-12" style="background-color:rgba(68, 70, 79,0.4);padding-left:50px;padding-top:5px;border-radius:5px;height:100%;"> <h3>KEYBOARD SHORTCUT INFO</h3>< ...

Can theme changes be carried over between different pages using Material UI?

I've encountered an issue with MUI 5.14.1 where I'm getting an error every time I attempt to save themes across pages using localStorage. Any suggestions on how to resolve this problem or recommendations on a different approach would be greatly a ...

Is there a way to change the button design within the CSS code of Mailchimp's embed feature?

Struggling to customize the button style and positioning in Mailchimp's embed CSS: <!-- Begin Mailchimp Signup Form --> <link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/c ...

Arrangement of Headers in HTML5

Take a look at this example of a webpage from my site: <html> <title> artilce header </title> <body> <header> <h1> nme of website</h1></header> <section> <h2> name of section&l ...

create a miniature display featuring text and visuals using HTML

Currently, I am in the process of developing a website and require assistance. My goal is to have a small screen appear with text and images whenever a link is clicked, similar to the functionality found in Chrome's "chrome://settings/startup". Howeve ...

Single Page Site - navigation to distinct sections with 'placeholder' pages

As part of a school project, I have been tasked with designing a website. My goal is to create a single-page website, but we are required to link to different pages like contact.html. I also want the page to smoothly scroll to the navigation section when a ...

Interacting with API using Ajax and jQuery

I am struggling to get my simple jQuery request to work correctly. I'm not sure what I'm doing wrong. Can you help me identify the error? http://jsfiddle.net/k6uJn/ Here is the code snippet: $(document).ready(function() { $.ajax({ type: "G ...

Extension for Chrome - Personalized pop-up notification when page loads

I am looking to create a custom alert box that triggers on page load instead of the default one, which I find unattractive and possibly irritating for users. alert('hello'); My current approach involves the following code: manifesto.js "cont ...

Select an image from the browser using JavaScript, adjust its size, and then transmit it to the server. Finally, utilize PHP to properly save the image

I am currently tackling the challenge of implementing a classical feature where users can select a file in their browser ("Browse"), have JavaScript resize it to a maximum width/height of 500 pixels, upload it to the server, and then save it to disk using ...

What is the appropriate way to notify Gulp when a task has been completed?

I have been working on developing a gulp plugin that counts the number of files in the stream. Taking inspiration from a helpful thread on Stack Overflow (source), I started implementing the following code: function count() { var count = 0; function ...

Issues observed when integrating Axios custom instance with Next.js

Initially, I created a custom axios instance with a baseURL and exported it as shown below: import axios from 'axios'; const instance = axios.create({ baseURL: process.env.BACKEND_URL, }); instance.defaults.headers.common['Authorization& ...

Utilize the Flexbox Grid with Bootstrap 4 Alpha CDN for Enhanced Layouts

Hi there everyone, I have a question about enabling Flexbox grid for Bootstrap 4 while using the CDN. Typically, I would utilize NPM to include the Flexbox Sass file and then import them into my primary Bootstrap Sass file. However, I am struggling to fig ...

Converting Typescript objects containing arrays into a single array

Looking for some assistance with this problem :) I am trying to convert the object into an array with the following expected result: result = [ { id: 'test-1', message: 'test#1.1' }, { id: 'test-1', mess ...

Deselect the tick marks on the dropdown box for material selection

I need help implementing a function for a click event that will unselect all items. <mat-autocomplete [panelWidth]='290' panelClass="myPanelClass"> <mat-option *ngFor="let item of items" [value]="item.name&qu ...

"Using jQuery to enable ajax autocomplete feature with the ability to populate the same

I am encountering a problem with jQuery autocomplete. It works perfectly fine with one textbox, but when I create multiple textboxes using jQuery with the same ID, it only works for the first textbox and not the others. My question is how can I create mult ...

Struggling with Incorporating Bootstrap into Django 3

I recently decided to implement Bootstrap into my project and came across this library which seemed promising. However, when attempting to use one of the template tags, I noticed that there was no styling applied, only plain HTML elements. So far, I have t ...

DIV collapsing in reverse order from the bottom to the top

Looking for some help on how to create two links that, when clicked, will scroll a hidden <div> up to fill the full height of its parent container. I've been having trouble with the element using the full height of the <BODY> instead. ...