Issue encountered when checking ng-minlength with Angular property is undefined

Attempting to validate user input in my angular controller, ensuring that the user has entered at least 5 characters. If less than 5 characters are inserted, a warning message should be displayed. Here is my controller code:

var app = angular.module('myapp', ['ui.bootstrap']);
app.controller('FeedController', function ($scope, $http) {

    $scope.customPostText = "";
    $scope.sendMessage = function()
    {
        console.log("text ");
        console.log($scope.customPostText);
        var length = $scope.customPostText.length
        //could us:
        //if ($scope.postcommentForm.customPostText.$valid) instead to check if valid
        //but I want to see the length.
        if(length >4 && length < 255)
        {
            alert("not undefined");
        }
        else
        {
            alert("message needs 5 characters you have."+length);
        }
    }
});

Encountering an issue where $scope.customPostText becomes undefined if less than 5 characters are typed, resulting in an error being logged:

Cannot read property 'length' of undefined

This issue is due to using ng-minlength in the HTML:

<div ng-controller="FeedController">
    <div class="row">
      <form id="postcommentForm" name="postcommentForm">
        <div class="form-group">
          <div class="input-group" id="post-comment-textarea">
            <textarea class="form-control"  name="customPostText"  id="customPostText" maxlength="255"
                      ng-model="customPostText"
                      ng-minlength="5"  
                      ng-maxlength="255" 
                      ng-trim="true"
                      ng-class="{ 'success-border': postcommentForm.customPostText.$valid ,'error-border': !postcommentForm.customPostText.$valid }"   
                      ng-required="true"                              
                      ></textarea>
            <span class="input-group-addon  btn btn-success" 
                  ng-disabled="{{postcommentForm.customPostText.$valid == false}}" 
                  ng-click="sendMessage()"
                  ng-class="{ 'success-border': postcommentForm.customPostText.$valid ,'error-border': !postcommentForm.customPostText.$valid }"   >
              Send
            </span>

          </div>
        </div>
      </form>
  </div>
</div>

Fiddle

The challenge lies in utilizing ng-minlength for validation while avoiding issues with value becoming undefined. This is necessary for the ng-class validation:

ng-class="{ 'success-border': postcommentForm.customPostText.$valid ,'error-border': !postcommentForm.customPostText.$valid }" 

Any suggestions on how to leverage ng-minlength without encountering this problem?

Answer №1

The validation for minimum length ensures that only valid content is sent, preventing sending undefined values.

One method to address this issue is:

var inputLength = angular.isDefined($scope.customPostText) ? $scope.customPostText.length : 0

By using this approach, you will receive a value of 0 when no valid input is entered in the field.

Answer №2

Indeed, the issue arises from the ng-minlength directive used in your code. It only assigns a value to the ng-model if it meets the minimum length requirement. Unfortunately, altering this default behavior may not be possible.

A workaround solution would be to eliminate the min length restriction. Instead, you can create a toggle variable in the controller like so:

if(length >4 && length < 255)
    {
         $scope.length_valid = true; 
         alert("not undefined");
    }
    else
    {
         $scope.length_valid = false; 
         alert("message needs 5 characters.");
    }

Subsequently, in the HTML file:

ng-class="{ 'success-border': postcommentForm.customPostText.$valid && length_valid ,'error-border': !postcommentForm.customPostText.$valid || !length_valid }" 

Answer №3

Set your variable using the form name like this: $scope.postcommentForm.customPostText in your JavaScript code.

This will ensure that it is never undefined.

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


app.controller('FeedController', function ($scope, $http) {


$scope.customPostText = "";
$scope.sendMessage = function()
{
    console.log("text ");
    console.log($scope.postcommentForm.customPostText);
    var length = $scope.postcommentForm.customPostText.length
    if(length > 4 && length < 255)
    {
                alert("not undefined");
    }
    else
    {
        alert("Message must have at least 5 characters.");
    }
}

});

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

Manual bootstrapping in AngularJS 1 is ineffective

I am a beginner with angularjs. I attempted to create 2 separate modules in a single js file and then manually bootstrap one of them to an element. This method was suggested in a stackoverflow post. However, it seems to not be working. Each of the modules ...

Display Image based on AngularJS value

Within my data, there exists a value {{catadata2.EndorsementList['0'].Rating}}. This value can be either 3, 4, or 5. Based on this value, I am looking to display the image <img src="/assets/img/rating.png" /> a certain number of times. For ...

Examine the syntax of JavaScript

I've been digging into a piece of code written by another person. My focus is on uncovering the JavaScript function that executes when the link below is clicked.... <a href="#subtabs_and_searchbar" id="finish_counting" onclick="$(' ...

There seems to be an issue with the transaction payload in the Cardano wallet when submitting an

I am attempting to send a previously signed transaction from cardano-cli using the cardano-wallet endpoint: https://localhost:8090/v2/proxy/transactions Here is how the signed transaction appears: txBody = { "type": "Tx MaryEra&q ...

The JSON data in ajax is not formatted correctly

Hey everyone, I'm facing a really frustrating error. I have a JSON formatted array that I'm passing from a PHP script to JavaScript through AJAX. Despite validating the JSON output, I keep encountering an error at the jQuery.parseJSON() step, whi ...

Mistakes in design when transforming inline SVG to PNG format

One of my main objectives is to convert a <div> element that contains multiple inline svg images into a png file. The entire process must be carried out within the client's browser using JavaScript. I have experimented with various techniques: ...

Using $regex in mongodb's pipeline operations allows for advanced string

I need to be able to use $regex in order to search for any words that contain a specific keyword provided by the user, but I'm experiencing issues. Here's what I have so far: aggregatePipeline.push({ $match: { name: { $reg ...

Having trouble performing a PUT request using AngularJS $http.put? Getting an error message saying "Invalid JSON

Recently, I have developed a service with the following functionality: app.factory('savedPropertiesService', ['$http', function ($http) { var sessionId = $('input[name=SessionGuid]').val(); var contactId = $('inp ...

Assistance Required for Making a Delicious Cookie

Within my interface, there are two buttons displayed - one is labeled yes while the other is called no. <input type="button" name="yes" onclick="button()"> <input type="button" name="no"> In order to enhance user experience, I am looking to i ...

Ways to verify the element prior to the completion of the request?

Utilizing Angular and Playwright Within my application, I have incorporated 2 buttons - one for delete mode and another for refreshing. Whenever the user triggers a refresh action, the delete mode button is disabled. Once the request returns, the delete m ...

Creating a dynamic dropdown menu to display nested arrays in Vuejs

I have some important data https://i.sstatic.net/Cq2t6.png Challenge I'm facing difficulty in accessing the tubes array within my data Solution script data() { return { types: [] } }, m ...

Problem with building Ionic v1 app

Hey there, I hope you're doing well. I've been working on an old Ionic v1 project. This project used to have SMS features incorporated into it. However, after a recent Google update: I received Issue: Violation of the Permissions policy ...

Swapping two values of input forms in HTML using jQuery interchangeably

I need help figuring out how to dynamically update the values of two input fields on a form interchangeably. For example, if input one represents the current price of Bitcoins and input two represents USD, I want to be able to change the value of one input ...

The tab indicator in Material-UI fails to update when the back button is clicked

My code is currently functioning well: The tab indicator moves according to the URL of my tab. However, there is a peculiar issue that arises when the back button of the browser is pressed - the URL changes but the indicator remains on the same tab as befo ...

Issue with splitting an array and eliminating commas - angular/ReactJS

Console Error: Unhandled error during execution of mounted hook Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'split') It seems to work up until it comes across a group that has no data for continent. This looks ...

Protractor test fails to retain variable's value

I am currently executing a protractor test to validate the existence of a record in the grid based on a specific license number. However, I have encountered an issue where the value assigned to the rowNumber variable gets lost after traversing through all ...

The results obtained from using $http get are not the same as those obtained

While attempting to retrieve user reports using a User $resource, I encountered an unexpected object format in the returned result: {0: "n", 1: "a", 2: "m", 3: "e", 4: ",", 5: "e", 6: "m", 7: "a", 8: "i", 9: "l", 10: ",", 11: "p", 12: "a", 13: "r", 14: "t ...

Exploring the SEO implications of client-side routing in AngularJS or VueJS

Implementing client-side routing instead of server-side rendering means that the entire page isn't pre-forged for every client visit. Instead, data is fetched from the web app as needed. Here's an example snippet of what the HTML code might look ...

Customizing Tabs in Material UI v5 - Give your Tabs a unique look

I am attempting to customize the MuiTabs style by targeting the flexContainer element (.MuiTabs-flexContainer). Could someone please clarify the significance of these ".css-heg063" prefixes in front of the selector? I never noticed them before upgrading my ...

Is there a way to dynamically set the value of a React Material TextField in Auto Select mode?

Here is a React state: const [filterByInvoiceNo, setFilterByInvoiceNo] = useState( 0 ); This represents a React Material TextField: <TextField size="small" type="number" label="Invoice No&quo ...