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

Using Jquery to create an array containing all the items in the pager

192.168.1.1/home?page=1, 192.168.1.1/home?page=2, 192.168.1.1/home?page=3. Is there a way to create an array of only the new items on the pager? I am interested in storing only the elements with the class item-new into the array. To clarify further: I n ...

Discovering a way to monitor keyup and keydown occurrences in JavaScript on an iPhone

Looking to track keyup/keydown events in JavaScript on iPhone browsers. My goal is to automatically move the focus to the next form element after the user has inputted the maximum number of characters in a text box. ...

Ajax UpdateProgress not functional

How can I resolve the issue where my AJAX UpdateProgress bar in ASP.NET is not running when executing a query in the correct format upon button click? Any solutions or help would be greatly appreciated. <html xmlns="http://www.w3.org/1999/xhtml"> ...

Parse a string and generate an array using regular expressions in JavaScript/Node.js

I'm currently working on coding in JavaScript to extract an array of elements after splitting using a regular expression. var data = "ABCXYZ88"; var regexp = "([A-Z]{3})([A-Z]{3}d{2})"; console.log(data.split(regexp)); The current output is [ &a ...

What is the best way to utilize Link for navigation in React with Material UI?

const pages = ['home', 'menu', 'reservation']; <Box sx={{ flexGrow: 1, display: { xs: 'none', md: 'flex' } }}> {pages.map((page) => ( <Link component={Link} to='/'>Home</L ...

Make a copy of an array and modify the original in a different way

Apologies for my poor English, I will do my best to be clear. :) I am working with a 3-dimensional array which is basically an array of 2-dimensional arrays. My task is to take one of these 2-dimensional arrays and rotate it 90° counterclockwise. Here is ...

Unable to successfully submit a request for login information using an AJAX call

I need to capture the user ID and password entered by the user and send it to the Server. Here is the Javascript code I am using: <script> function Display(){ var ID = document.getElementById("user_id").value; document.getEl ...

JQuery Tic Tac Toe Duel: Face Off Against Your Friend in a Thr

Looking for some advice here. I'm new to game development and currently working on a 2 Player Tic Tac Toe game. I need help with implementing the game functionality. Any suggestions? I want to disable the "div" once a player clicks on it, but I' ...

I'm looking to create a Vuex getter to retrieve data from the Google API documentation – can you help

Can someone help me figure out how to create a getter in Vuex store with flat data from the Google Docs API? My goal is to extract the textRun content and store it in an array because there will be multiple messages. Currently, I have hard coded this respo ...

Ensure that every HTML link consistently triggers the Complete Action With prompt on Android devices

After extensive searching, I have yet to find a solution to my issue. I have been developing a web application that allows users to play video files, primarily in the mp4 format. Depending on the mobile browser being used, when clicking the link, the vide ...

Troubleshooting: ng-init function not functioning properly with AngularJS

Review my code: JSON var jsonData = '[{"type":"product","id":1,"label":"Size","isRequired":true,"errorMessage":"","enablePrice":true,"description":"","placeholder":"Select Size","defaultValue":"","choices":[{"text":"Size 30","value":"Size 30","isSel ...

Utilize pivot to manage user roles and permissions in ExpressJS application using Mongoose

My user schema is structured as shown below const userSchema = mongoose.Schema({ username: { type: String, required: true, }, first_name: { type: String, required: true, }, last_name: { type: Stri ...

Laravel triggers a 'required' error message when all fields have been filled

As I attempt to submit a form using an axios post request in laravel, I encounter an issue with the validation of the name and age fields, along with an image file upload. Here is a breakdown of the form structure: Below is the form setup: <form actio ...

Issue with the alphabetical ordering of subpages

My PageSidebar.js component lists child pages alphabetically. https://i.sstatic.net/DZro1.png However, when I navigate to a child page, the alphabetical order is not maintained. https://i.sstatic.net/fRVgO.png I've tried multiple solutions but hav ...

Use Javascript to toggle the display to none for a specific table row (tr)

Is there a way to implement JavaScript code that will hide a specific table row using display:none;, and then reveal it again when a button is clicked? ...

What does the error message "TypeError: Bad argument TypeError" in Node's Child Process Spawn mean?

Every time I execute the code below using node: var command = "/home/myScript.sh"; fs.exists(command, function(exists){ if(exists) { var childProcess = spawn(command, []); //this is line 602 } }); I encounter this error: [critical e ...

Cannot extract the 'name' property from 'e.target' because it is not defined

I encountered an error message stating that I cannot destructure the property 'name' of 'e.target' because it is undefined within the createform() method. Despite highlighting the line causing the error, I am still unable to comprehend ...

Extracting data from input fields in forms

I am dealing with a set of form inputs that are being generated in the following way: For a better understanding, please refer to UPDATE 2 below for the complete component. If there are three columns present, then three groups of these inputs will be dis ...

"Discover the best way to sort through an array of complex objects with varying levels of nesting using a specified search

I have come across similar answers, but none of them go beyond two levels deep. Therefore, I believe this is not a duplicate problem. My task is to filter an array of objects where each object may contain nested objects of unknown depth. In my data structu ...

React Apollo Error - When using refetchQueries, data does not re-render in one component but does so in another. Surprisingly, it works when the refetchQueries is in the same

Within my application, there is a Main Component that displays a list of todos. Additionally, the Sidebar Component showcases various products as illustrated below ...