How can I restrict validation to trigger only when a field loses focus?

Is there a way to validate the input tag for time format 00:00:00 after exiting the field, rather than during user typing? Any suggestions on how to accomplish this?

  <label for="operativeToTime">Operative to time</label>
    <input name="operativeToTime"
           ng-model="deviceDetails.operativeToTime"
           type="text"
           ng-pattern="/^(?:2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9]$/"
           ng-required="true">
    <div class="error-container" ng-show="editDeviceForm.operativeToTime.$invalid">
        <span class="error" ng-show="editDeviceForm.operativeToTime.$error.required">Operative to time is required</span>
        <span class="error" ng-show="editDeviceForm.operativeToTime.$invalid">+++++++++++++Wrong format</span>
     </div>

Answer №1

To achieve the desired outcome, utilize ng-blur which is a pre-built functionality in AngularJS: https://docs.angularjs.org/api/ng/directive/ngBlur

<label for="operativeToTime">Operative to time
    <input name="operativeToTime"
           ng-model="deviceDetails.operativeToTime"
           type="text"
           ng-required="true"
           ng-blur="validateInput(this)"/>
    <div class="error-container" ng-show="editDeviceForm.operativeToTime.$invalid">
        <span class="error" ng-repeat="error in errors" ng-bind="error"></span>
     </div>

Update - included JS code as per OP's request: To bind error messages to your span element, implement the following JavaScript:

$scope.errors = [];
$scope.validateInput = function(element){
var validate1 = //your validation logic goes here
if(!validate1){
  $scope.errors.push("Error message 1");
}
var validate2 = //your validation logic goes here
if(!validate2){
  $scope.errors.push("Error message 2");
}
};

Answer №2

I approached this problem with a unique solution, utilizing a custom directive to maintain a DRY codebase. Here is the code snippet I used:


app.directive('checkTimeOnBlur', function () {
    var EMAIL_REGX = /^(?:2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9]$/;
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, elm, attr, ctrl) {

            if (attr.type === 'radio' || attr.type === 'checkbox') return;
            elm.unbind('input').unbind('keydown').unbind('change');

            elm.bind('blur', function () {
                scope.$apply(function () {
                    if (EMAIL_REGX.test(elm.val())) {
                        ctrl.$setValidity('time', true);
                    } else {
                        ctrl.$setValidity('time', false);
                    }
                });
            });
        }
    };
});

To implement this in the view:

<input type="text" name="time" ng-model="user.time" check-time-on-blur>
<span ng-show="editDeviceForm.time.$error.time" class="help-inline">Invalid time!!!</span>

This solution was inspired by the following plnkr example: http://plnkr.co/edit/A6gvyoXbBd2kfToPmiiA?p=preview

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

Adjust the font size based on the dimensions of the container

I'm currently working on a script that dynamically sets the font-size based on the container's dimensions and the length of the text. This is what I have implemented so far. window.onload = function () { var defaultDimensions = 300; ...

Comparing non-blocking setTimeout in JavaScript versus sleep in Ruby

One interesting aspect of JavaScript is that, being event-driven in nature, the setTimeout function does not block. Consider the following example: setTimeout(function(){ console.log('sleeping'); }, 10); console.log('prints first!!') ...

Organizer featuring Outlook-inspired capabilities

My goal is to develop a system for efficiently managing appointments. Upon opening the application, I want to display a calendar control that will retrieve an individual's schedule from a SQL server database. For example, if the user has meetings sch ...

connecting elements in an object's array to another array within a nested object

Is there a way to iterate through each string value in the imageKeys array and use it to create a URL for each object in the images array within the nested ImageList object, all without changing the original object? const myInitialStateFromParent = { ...

What is the best way to incorporate a JavaScript file into my ejs file using node.js?

As I work on creating a website for my school project, I encountered a challenge involving including CSS files in node.js. Thankfully, after researching on stackoverflow, I was able to find a solution. Now, I am facing another issue - how to include a java ...

Adding elements from one array to another array of a different type while also including an additional element (JavaScript/TypeScript)

I'm having trouble manipulating arrays of different types, specifically when working with interfaces. It's a simple issue, but I could use some help. Here are the two interfaces I'm using: export interface Group { gId: number; gName: st ...

Show or hide a div through two variables that toggle between different states

It's possible that I'm not fully awake, so missing the obvious is a possibility. However, I have 2 variables that determine whether a div has a specific class or not. The class functions more like a toggle; so the following conditions should tri ...

What is the process for running a script during partial view rendering?

My view is strongly typed to a CalculateModel where a user inputs information and then makes an ajax post to the controller. The controller performs calculations using this data and returns a PartialView strongly typed to the ResultCalculateModel. The Res ...

What is the best way to incorporate a rectangle or arrow into my canvas design?

Looking for a way to enhance my html canvas wind direction code, here is how it currently looks: var x, y, r, ctx, radians; ctx = window.compass.getContext("2d"); radians = 0.0174533 * (10 - 90); x = ctx.canvas.width / 2; y = ctx.canvas.height / ...

Can you please explain the process of retrieving the value of an item from a drop-down menu using JavaScript?

I am currently developing a basic tax calculator that requires retrieving the value of an element from a drop-down menu (specifically, the chosen state) and then adding the income tax rate for that state to a variable for future calculations. Below is the ...

Encountering Rendering Issues with EJS Post HTML Conversion

After working on a much larger project for over a month, I'm now six hours into troubleshooting and everything is starting to blend together. Prior to switching to EJS, everything was working perfectly. I'm not looking for someone to solve the ...

Easily transition the header's height when selecting a menu item

I am trying to achieve a collapse effect or something similar However, when I click on a menu item, the height changes too quickly without any animation What could be wrong in my code? I am looking to reference an effect similar to the one seen in the h ...

What is causing the React text component to fail to show changes made to my array state?

I am currently in the process of learning React Native. I have been working on an app and encountered an issue while attempting to update individual elements within an array. Here is an example of the code: function MyApp() { const [array, setArray] = ...

Leveraging ngCordova in a Cordova Application

As I work on implementing ngCordova into my cordova application, I am encountering an issue where I receive the error message "device is undefined" when making the following call: var app = angular.module('app', ['ngCordova'])... app. ...

Dividing a sentence by spaces to isolate individual words

Recently, I encountered a challenging question that has me stuck. I am working on creating an HTML text box where the submitted text is processed by a function to check for any links. If a link is detected, it should be wrapped in anchor tags to make it cl ...

Jesting around with mocking console.error leads to test failures

The Issue: Currently, I am working on testing React components using Jest and Enzyme. In order to check for properties in development, I have incorporated the prop-types module. The prop-types module relies on console.error to alert when mandatory props a ...

Enhancing websites with font-awesome icons and upgrading from older versions to the latest

Seeking guidance on updating our project to use the latest Macadmine theme. The transition from Font Awesome 3 to Font Awesome 4 requires changing all icons to their proper names. I came across a helpful resource at https://github.com/FortAwesome/Font-Aw ...

Performing an Ajax post request to a PHP script in order to retrieve a PHP variable using XMLHttpRequest

I am looking to dynamically update my table using JavaScript every few seconds. Currently, I have set up an AJAX post request to my update.php file and trigger it if it is set. Then, I execute a MySQL query to retrieve the data and store the resultset in ...

When transitioning in Vue, pagination bullets shift to the left upon changing routes

While using Vue 3 and swiper.js, I encountered an issue where the pagination bullets move to the left when the route changes (component unmounted). It appears that the styling for the bullets and active button also disappear. I have created a reproduction ...

An expected expression was encountered near the if condition

I am encountering an expression expected error in Visual Studio near if(isNullOr ........ if (value) { if (isNullOrUndefined(x.value) && isNullOrUndefined(x.value2)) { x.minMark + '-' + a + '*' + x.b + ' ' + ...