Validating length in AngularJS - angularjs

I have a directive which is used for text field and the directive has a validation like below which should show a message when the textfield length is less than 5 characters.
attrs.$observe('useNumberRegex', function( val ) {
scope.useNumberRegex = GenericFieldUtils.castBoolean(val, false);
if(scope.useNumberRegex)
{
scope.regExp = /^\d+$/;
}
});
and the directive template URL points to html as shown below
<li ng-if="editable && (cssClass == 'text_style_filter' || cssClass == 'drp_down_style')" style="float:left;width:42%" class="{{$parent.cssClass}}">
<input id="{{$parent.uniqueId}}" name="{{$parent.name}}" type="{{$parent.textType}}" class="field-control {{$parent.numCssClass}}" ng-pattern="$parent.regExp" autocomplete="off" ng-required="mandatory" ng-maxlength="{{maxLength}}" maxlength="{{maxLength}}" ng-model="$parent.value" ng-disabled="disabled" ng-blur="$parent.onBlur($parent.value)" ng-keyup="$parent.onKeyup($parent.value)" aria-label="{{$parent.ariaLabelInput}}" min="{{min}}" max="{{max}}" validate>
<div ng-if="$parent.formController.submitController.attempted">
{{$parent.regExp}}
<span class="error-message" ng-repeat="error in errors" translate>{{error}}fdsfsdfsdf</span>
</div>
</li>
Can you please help me what is going wrong in displaying a message when the length is less than 5 characters long.

You can use ng-minlength to actually validate the length of the input.
You could also use the regex pattern to validate the same. Instead of /^\d+$/ use /^\d{5,}$/

Related

Angularjs $viewValue.length for form validation

I have a simple from to which I am trying to add validation. I am comparing the $viewValue in the form with the value of ng-min/mg-max to notify the user if he is trying to enter values that are over the max and under the min allowed. The issue is that if I use ng-if="myform.$viewValue.length > maxvalue" the error does not appear. However, the error DOES appear when I exclude .length() However, in this case it is checking every integer in of $viewValue string with maxvalue number, which is not intended. I understand that $viewValue.length would give me a number instead of a string so that I may compare a number with a number, but in this case the error never appears.
I even have a JSFiddle example that works https://jsfiddle.net/up2qxcxe/
But it does not in my app.
Here is my form:
<form name="modelParamsForm" novalidate>
<div class ="row">
<div class="form-group col-md-4" ng-repeat="modelParam in
modelParams" ng-class="{ 'has-error' :
modelParamsFieldForm.value.$invalid }">
<ng-form name="modelParamsFieldForm">
<label form-group>{{modelParam.label}}</label>
<input type="number" class="form-control input-sm"
ng-model="modelParam.value" name="value"
ng-min="modelParam.minvalue" ng-max="modelParam.maxvalue" >
<span ng-show="modelParamsFieldForm.value.$invalid"></span>
//MIN-MAX VALIDATOR
<div ng-if="modelParamsFieldForm.value.$viewValue.length >
modelParam.maxvalue">Max exceeded:{{modelParam.maxvalue}}
</div>
</ng-form>
</div>
</div>
My controller is nothing special:
$scope.modelParams = {};
$scope.loadModelParams = function(modelName) {
var req = {
method : 'GET',
url : urlPrefix + 'PB_OPTIMISER_GET_MODEL_PARAMS',
params: {modelName : modelName}
};
$scope.loading = true;
$http(req).then(function(response) {
$scope.loading = false;
$scope.modelParams = response.data;
$scope.modelParamsOld = angular.copy($scope.modelParams);
}, function() {
$scope.loading = false;
});
};
EDIT: In my JSON modelParam.maxvalue is a string. I think the problem was that I am comparing a myform.$viewValue.length with modelParam.maxvalue which is string type. I am not sure how to get around this...do I have to parse maxvalue?
You do not need $viewValue. Your ng-ifs are wrong. Change to
<input type="number" class="form-control input-sm col-md-5" ng-model="modelParam.value" name="test" min="modelParam.minvalue" max="modelParam.maxvalue">
<span ng-if="modelParam.value > modelParam.maxvalue">Too Many!!</span><br>
<span ng-if="modelParam.value < modelParam.minvalue">Too Few!!</span>
It should work fine. Here is your Plunker working the way I think you want.
The problem here is that the modelParam.maxvalue was coming from the database as a string, rather than integer. So when comparing ng-if="myform.$viewValue.length > modelParam.maxvalue" I was comparing an integer with a string, and that obviously did not produce the desired results. The solution was to go to the table and make maxvalue an integer.
Alternatively one can have a second variable for maxvalue in the controller that parses the string like so: $scope.mpMaxValue = parseInt($scope.modelParams.maxValue)
See this post for a longer discussion: AngularJS comparing $viewValue against ng-model or object param

Angular - Checking if a field is empty

Bit of a trivial one here however am new to Angular so excuse me.
Whenever I have an input field - I only want an action to occur if the field actually contains some valid content.
What i find I'm having to do is first instantiate a variable, then assign that to whatever input there is then do a boolean check in a if.
Is the the correct way to go around this? If i don't instantiate the variable (or don't use one at all) i run into getting undefined error:
var textToSearch = '';
textToSearch = $scope.main.searchInputField.trim();
if (textToSearch){
$location.path('/search/'+textToSearch);
}
Also (on another note)
I'm sanitising everything on the server side however on Angular/client side is there a quick and easy function I can use?
Thanks
I suppose you have an ng-model for 'main.searchInputField' so if you want to check if the field is empty you can just write
$scope.main = {};
if($scope.main.searchInputField.trim().length > 0){
//do stuff
}
suppose you have ng-model of input field 1 as some.data and input field 2 as some.data1
for(var i=0; i<$scope.some.length;i++){
if($scope.some[i]){
//do something
}
}
it will check every field.
This is using Bootstrap for email validation, but the same logic applies if you are using your own classes.
<div ng-class="(emailRegExp.test(email) && email != null) ? 'has-success' : 'has-error'" class="form-group has-feedback">
<div class="input-group">
<div class="input-group-addon">
<span class="glyphicon glyphicon-envelope"></span>
</div>
<input ng-model="email" ng-change="checkEnableSubmit()" id="email" placeholder="Email Address" type="text" class="form-control" aria-describedby="emailStatus">
</div>
<span ng-class="(emailRegExp.test(email) && email != null) ? 'glyphicon-ok' : 'glyphicon-remove'" class="glyphicon form-control-feedback" aria-hidden="true"></span>
</div>
The ng-class directive accomplishes the validation if:
The checkEnableSubmit() function in your controller only allows a submission when the data is valid (I would be happy to include that code, too)
Both classes in the ternary operator on line #1 indicate valid data and non-valid data (in this example one makes the input appear green and the other red)

Validate textarea with Angular ng-messages when using Tinymce (ui-tinymce)

How to validate using ng-messages like ng-maxlength when the <textarea> has a ui-tinymce attribute?
Or is there a better way?
<div class="form-group">
<div class="col-sm-12">
<label>Description</label>
<p class="small">Please provide as much detailed information as possible.</p>
<textarea name="description" class="form-control required" ui-tinymce="tinymceOptions" ng-model="aC.testData.description"
ng-maxlength="100" required></textarea>
<div class="help-block" ng-messages="mainForm.description.$error" ng-show="mainForm.description.$touched">
<p ng-message="required">A description is required.</p>
<p ng-message="maxlength">Description must not exceed 100 characters.</p>
</div>
</div>
</div>
The issue you are seeing is that the standard directives just count characters so a simple (empty) HTML sample:
<p></p>
Would indeed show as 7 characters when in reality there is no "visible" content. I built a custom directive for another editor and what I ended up doing is using jQuery's .text() function against the HTML. This removes all of the HTML tags and provides an approximation for the number of actual text characters in the editor. This is a portion of the code in the diective:
var jStrippedString = jQuery(modelValue).text().trim();
return (maxlength < 0) || ngModelCtrl.$isEmpty(jStrippedString) || (jStrippedString.length <= maxlength);
I believe that you would want to create a custom Attribute directive that allows you to grab the model data for the editor and perform this validation yourself.
Adding forced_root_block: "" to the tinymce options should also work. By default it will not add <p></p> from the start.

Angularjs Input text appending number instead of adding it

When user type in number then click on "+", it will append the count instead of perform addition for the counter.
But it is working fine when performing "-" or "+" action without key in number in the input box.
<div ng-app="myApp" ng-controller ="myCtrl">
<span ng-click="count = count + 1">+</span>
<input type="text" ng-model="count" valid-number>
<span ng-click="count = count - 1" ng-show="count > 0">-</span>
</div>
fiddle : http://jsfiddle.net/shenglim/Lyugypqk/4/
Anybody can help out on this? Thanks !
simple example will work if uses ng-click="test()" and perform basic addition, if you need to retrieve from existing json which return string, Try to use parseInt() on the JSON object.
Try <input type="number">.
The data type for type="text" makes it a string and "1" + 1 = "11"
JSFiddle ~ http://jsfiddle.net/Lyugypqk/2/
Alternatively you can add two methods to increase and decrease the values into the controller and use them,
$scope.increment = function(){
$scope.count++;
};
$scope.decrement = function(){
$scope.count--;
};
<span ng-click="increment()">+</span>
<input type="text" ng-model="count" valid-number>
<span ng-click="decrement()" ng-show="count > 0">-</span>

Show ? in textbox when textbox have ng-pattern for numeric validation

I need to show '?' when the value not able to read from scanner which returns me value by including '?'
Let say document has sr no as '123' but let say for some reason scanner not able to read it then it returns me as "12?" or "???" or "?23" or "1?3"
If any digit which is not readable that need to corrected by user manually for that i need to show them in to the textbox.
In our application we are using angularjs validations, which are not allowing me to show above values inside textbox as it contains '?' which is not numeric value.
Also I should enforce the numeric validation so that user can correct the above and submit to the server.
So how we achieve this functionality ?
<div ng-app ng-controller="formCtrl">
<form name="myForm" ng-submit="onSubmit()">
<input type="text" ng-model="price" name="price_field" ng-pattern="/^[0-9]{1,7}$/" required>
<span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span>
<input ng-show="toggle" type="submit" value="submit"/>
<input ng-show="!toggle" type="button" ng-click="AfterProcessing()" value="After Processing"/>
<input type="button" value="Reset" ng-click="reset()"/>
<br/>
<span>Activity : {{message}}</span>
</form>
</div>
JS code
function formCtrl($scope){
$scope.price= "123";
$scope.toggle = false;
$scope.message="No Activity";
$scope.onSubmit = function(){
$scope.toggle=false;
$scope.message="onSubmit clicked...";
}
$scope.AfterProcessing = function(){
$scope.toggle=true;
$scope.price ="1?3";
$scope.message="AfterProcessing clicked...";
}
$scope.reset=function()
{
$scope.toggle=false;
$scope.price ="123";
$scope.message="Reset clicked...";
}
}
I have created sample as below.
Plz check on JsFiddle sample
-Thanks
You need to create a CSS Class that will be applied to text box. Using :before and :after pseudo css construct, you can add ? character and get desired result.
So,
1. Define a CSS Class with :before and/or :after as per your requirement
2. On the HTML, use ng-class="{'your-class': $error, 'regular-class': '$pristine'}"
Let me know if you need a code sample and a plunker. (I am at the end of the day. May be will provide some code tomorrow. )
If you can create a plnkr based on above and submit link here, more people would be able to help you. thanks.

Resources