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>
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?