Custom validation preventing Ng-minlength from functioning correctly

I'm currently working on an angularJS project where I am trying to create a form for users to input their username. The application needs to validate if the username is available in the database and if it falls within a character length of 5 to 10.

<input type="text" name="uname" ng-model="user.uname"
ng-minlength="5" ng-maxlength="10" uniqueusername required/>

The uniqueusername directive is responsible for checking if the username is available:

app.directive('uniqueusername', function($http){
return{
    require : 'ngModel',
    restrict : 'A',
    link : function(scope,elem,attrs,ctrl){
        ctrl.$parsers.unshift(function(value) {
            $http.get('/api/check'+value).success(function(data,status){
                if(data.available=='true'){
                    ctrl.$setValidity('unique',true);
                }
                else{
                    ctrl.$setValidity('unique',false);
.........................................................................

Currently, I have noticed that when I input a username with less than 5 characters, it is still considered valid. This should not be the case. Interestingly, everything works perfectly fine when I remove the uniqueusername directive from the input field.

Thank you for your responses.

Answer №1

Make sure to remember that the parser function must have a return value:

app.directive('checkavailability', function($http){
    return{
        require : 'ngModel',
        restrict : 'A',
        link : function(scope,elem,attrs,ctrl){
            ctrl.$parsers.unshift(function(value) {
                $http.get('/api/verify'+value).success(function(data,status){
                    if(data.available=='true'){
                        ctrl.$setValidity('available',true);
                    }
                    else{
                        ctrl.$setValidity('available',false);
                    }
                });
                return value;
            };
        }
    });

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

The error message "TypeError: addNewUser is not a function in React.js onSubmit

What could be causing the error message "TypeError: addNewUser is not a function"? The issue arises when I complete the form and click save, displaying the error that addNewUser is not defined as a function. The problem occurs within the following code ...

What is the best way to utilize MUI breakpoints for displaying images based on different screen sizes?

I need help displaying an image based on the screen size using MUI breakpoints. I'm struggling to understand how to implement this with MUI. Can someone assist me with the breakpoints? interface EmptyStateProps { title: string; description: string ...

Combine two arrays that have been transformed using mapping in JavaScript

Is there a way for me to utilize the useState hook in order to save and combine two arrays? I have managed to individually fetch and store values from the one and two arrays, but I am struggling to concatenate them into a single array. My ultimate goal i ...

Stop span elements from being removed within a `contenteditable` container

I am facing a challenge with an editable div that contains a span element which I would like to prevent users from deleting. My development environment is Vue3. Currently, if the user presses backspace while their cursor is to the right of the span or sel ...

What is the reason for React.Component being implemented as a function rather than an ES6 class?

After delving into the codebase of React, I made an interesting discovery. When you define a class like class App extends React.Component, you are essentially extending an object that is generated by the following function: function Component (props, cont ...

Angular controller is failing to receive the dynamic JSON response from the RestAPI

Currently, I am working with JSON data retrieved from a REST API. I have successfully set up an alert that displays the JSON results within an $http.get function. Using a sample URL that contains test JSON data works perfectly fine and I receive the alert ...

Capture and store the current ionic toggle status in real-time to send to the database

I have a list of names from the database that I need to display. Each name should have a toggle button associated with it, and when toggled, the value should be posted back to the database. How can I achieve this functionality in an Ionic application while ...

Having trouble with using findByIdAndUpdate and push in MongoDB?

As someone who is new to Mongodb, I have been using the findByIdAndUpdate function to update a document in my project. However, I noticed that it returns the old document instead of the updated one. Below is the code snippet of my function: exports.crea ...

Filter the array and determine the number of elements in the filtered array

I am looking to filter the contents of two arrays and then count the elements where "isimplemented: 'Yes'" is true: const array1 = [{ProjectName: "IT", Department: "Software"}] const array2 = [{Name: "IT", isimplemented: "Yes"}] The method I at ...

Unable to access current props within useEffect block

When I use useEffect with the parameter props.quizStep, my function fn (which is a keydown event listener) is unable to access the current value of props.quizStep. I'm puzzled as to why it's not working properly. Can you help me understand? Bel ...

Determine the duration/length of an audio file that has been uploaded to a React application

I am working on a React web application built with create-react-app that allows users to upload songs using react-hook-forms. The uploaded songs are then sent to my Node/Express server via axios. I want to implement a feature that calculates the length of ...

Avoiding memory leaks in Reactjs when canceling a subscription in an async promise

My React component features an async request that dispatches an action to the Redux store from within the useEffect hook: const fetchData = async () => { setIsLoading(true); try { await dispatch(dataActions.fetchData(use ...

Preserve the iframe src value in the dropdown menu even after the page is refreshed

I am trying to figure out how to prevent the iframe src from changing when I refresh the page, unless the user manually changes it using the dropdown menu with JavaScript. Can someone help me with this? <div class="row"> <div class="span9"> ...

Test whether a DOM element does not exist using unit testing

When working on my directive, I make use of element.remove() in certain situations to eliminate an element from the DOM. it('should remove the <img> tag', function() { //expect(element.find('img')) ?? }); What would be the b ...

When integrating string variables into JavaScript regular expressions in Qualtrics, they seem to mysteriously vanish

I have been working on a project to analyze survey responses in Qualtrics by counting the number of matches to specific regular expressions. For example, whenever phrases like "I think...", "In my opinion," are used, the count increases by one. Below is t ...

Tips for implementing lazy loading with an owl carousel featuring background images

Is there a way to add lazy loading to a semi custom owl carousel that uses background images instead of regular img tags? I've tried using Owl carousel's function for lazy loading but it doesn't seem to work. How can I achieve this? This is ...

I am having trouble resolving 'otp-input-react' in my project directory at D:projectappsrc

I have been troubleshooting this issue but haven't been able to find a solution yet. I even tried uninstalling and reinstalling the package, but it still isn't working as expected. Here are some images for better clarity: https://i.stack.imgur.c ...

Retrieving the values of a particular row in a table multiple times using angular JS and filters

I am currently making a call to an API that will provide me with a JSON object. From this JSON object, I am extracting values based on certain conditions and displaying them in a table using AngularJS. The challenge I am facing now is retrieving the data f ...

When does the ng-disable function become activated?

Here's an example: <button ng-disabled="!isSomethingValid() || loading || disabled" ... class="btn btn-primary"> What determines the condition for the ng-disable attribute to evaluate its expression? ...

Calculating and displaying the output on an HTML page: A step-by-step guide

Within my HTML, I have two values stored in Session Storage: "Money" and "Time". These values are based on what the user inputted on a previous page. For example, if someone entered that they need to pay $100 in 2 days. My goal is to generate a list that ...