I’m using angular.js and jQuery to validate user inputs in a form that is created using an ng-repeat. So essentially I have an array of strings(barcodes) I loop through and display, I also display an input field. The user is going to use a barcode scanner, think of it like a copy/paste effect, to enter strings into the input fields. If the barcode doesn’t match the string thats next to it than it should alert the user and clear the input field. I have the code below that uses ng-model-options ‘Blur’ to perform this and it almost works. Right now it alerts the user three times every time an inputs is incorrect. I cannot figure out why it fires three times? there must be a more elegant way of achieving this validation with angular/jQuery? maybe a directive? I’m new with angular so any help is greatly appreciated, Thanks!
HTML:
<div ng-repeat="(index, val) in barcodes.barcodes track by $index">
<div class="form-group row" ng-show="barcodes.barcodes[index]">
<div ng-if="barcodes.barcodes[index] != 'X'">
<label class="col-sm-3 form-control-label" style="margin-top:5px"> {{ barcodes.barcodes[index] }} </label>
<label class="col-sm-2 form-control-label" style="margin-top:5px"> {{ barcodes.A_adaptors[$index+8] }} </label>
<div class="col-sm-1" style="margin-top:5px">
<button class="btn btn-xs btn-default hvr-pop" data-toggle="dropdown" ng-click="getIndex($index+8)"><i class="fa fa-cogs" aria-hidden="true" style="color:#DF3D42"></i></button>
<ul class="dropdown-menu" role="menu">
<div ng-repeat="x in barcodes.B_adaptors">
<li class="text-center" ng-click="replace(x)" id="B_adaptors">{{ x }}</li>
</div>
</ul>
</div>
<div class="col-sm-6">
<input type="text" class="form-control matching" ng-model-options="{ updateOn: 'blur' }" ng-model="item.barcodeInput" placeholder="Barcode" required>
<div ng-show="!isEqualToBarcode($index+8, item.barcodeInput)"> Error: Barcode not the same! </div>
</div>
</div>
</div>
</div>
JAVASCRIPT: (in controller)
$scope.isEqualToBarcode = function(index, val) {
if(val === null || val === undefined) return true;
if($scope.barcodes.A_adaptors[index] !== val.trim()) {
console.log("wrong", val);
alert("Incorrect Barcode, Try Again.");
val = "";
}
return $scope.barcodes.A_adaptors[index] === val.trim();
}
One way is to change it to an angular form.
Angular gives input validation and flags for invalid input.
Here is a link to get you started
You can also define your own validator directives for the same.
https://docs.angularjs.org/guide/forms
It's because ng-show is expecting a boolean, functions don't usually work as expected in ng-show. Try putting the isEqualToBarcode function on the input inside an ng-blur event.
That being said a better solution would be to use angular's input/form validation, i briefly explained how to use it here but you might want to take a look at the documentation or a tutorial if you're completely new to it. The kind of validation you want doesn't come with angular out of the box, luckily other people have already created a custom directive to handle that. It was made for confirming a password but the basic functionality is still the same (matching 2 values). This might seem like the long way around but trust me it will save you a lot of trouble on the long run.
Related
I am trying this ,
<div ng-form="sadadPaymentForm" class="sadadPaymentForm" ng-if="vm.isSadadEnabled" name="sadadPaymentForm" validate-popup-form>
<div ng-if="vm.isSadadEnabled">
<div class="credit-debit-card-div" ng-include="'sadadTemplate'" ng-show="vm.view_tab == 'tab7'">
</div>
</div>
</div>
<span ng-show="vm.view_tab=='tab7' && vm.isSadadEnabled">
<button type="button" class="primary inline pay-now" id="paynowbtn" ng-disabled="!vm.checked3 || vm.sadadPaymentForm.$invalid" ng-click="vm.payByVoucher();" analytics-on="click" analytics-event="uaevent" analytics-eventcategory="Payment" analytics-eventaction="PayNow"
analytics-eventlabel="Pay now">
Pay by sadad
</button>
</span>
And , my template in another html file
<script type="text/ng-template" id="sadadTemplate">
<input fieldlabel="Online Payment ID" type="text" name="onlinePaymentId" ng-model="vm.sadadpayment.onlinePaymentId" class="form-control input-type-text"
ng-model-options="{ debounce: 100 }" validationKey-required="PaymentAdress1IsRequired" required maxlength="200">
</script>
Here the vm.sadadPaymentForm.$invalid does not work but Indidual components validation works on blur on blur of input .
BUT , if I add vm to ng-form ,ie like this
<div ng-form="vm.sadadPaymentForm" class="sadadPaymentForm" ng-if="vm.isSadadEnabled" name="vm.sadadPaymentForm" validate-popup-form>
<div ng-if="vm.isSadadEnabled">
<div class="credit-debit-card-div" ng-include="'sadadTemplate'" ng-show="vm.view_tab == 'tab7'">
</div>
</div>
</div>
Here the vm.sadadPaymentForm.$invalid works but Indidual components validation fails on blur of input for eg, TypeError: Cannot read property 'onlinePaymentId' of undefined
Help me understand how can I make both individual validation and the final form validation work together.Angular Ver 1.5,cannot upgrade this now.Need a solution with 1.5.
Form name attribute should have sadadPaymentForm inspite of vm.sadadPaymentForm. Since you don't have form name specified correctly, validation is failing.
name="vm.sadadPaymentForm"
should be
name="sadadPaymentForm"
Ok found out the issue , its basically a scope issue.
replaced
ng-if="vm.isSadadEnabled"
with
ng-show="vm.isSadadEnabled"
ng-if was preventing the DOM from rendering thus killing the scope variable vm itself
I have a page where I want to update a form with several radio buttons. I query an api, and use the returned array of objects to populate the current values for the radio buttons. The problem that I have is that only the last set of radio buttons actually shows the value. This is the code that I have (I am using [[ and ]] for the start and end symbols for angular):
<fieldset data-ng-repeat="s in sections">
<div class="form-group">
<div class="col-md-12">
<h2>[[ s.section.name ]]</h2>
</div>
</div>
<!-- Field Item -->
<div class="form-group m-b-20 bg-light" data-ng-repeat="f in s.fields">
<div class="col-md-12 m-b-30">
<h4>[[ f.field.name ]]</h2>
<input type="text" data-ng-model="f.comments" class="form-control input-md underline" placeholder="Comments">
</div>
<div class="col-sm-3">
<input type="radio" name="section-[[s.section.section_id]]-field-[[f.field.field_id]]" value="pass" class="form-control" data-ng-model="f.field_condition">
<label class="eval-pass"><i class="fa fa-check-circle green"></i> Pass</label>
</div>
<div class="col-sm-3">
<input type="radio" name="section-[[s.section.section_id]]-field-[[f.field.field_id]]" value="fail" class="form-control" data-ng-model="f.field_condition">
<label class="eval-fail"> <i class="fa fa-exclamation-circle red"></i> Fail</label>
</div>
<div class="col-sm-3">
<input type="radio" name="section-[[s.section.section_id]]-field-[[f.field.field_id]]" value="n/a" class="form-control" data-ng-model="f.field_condition">
<label class="eval-na"> <i class="fa fa-circle blue"></i> N/A</label>
</div>
<div class="col-sm-3">
<input type="radio" name="section-[[s.section.section_id]]-field-[[f.field.field_id]]" value="caution" class="form-control" data-ng-model="f.field_condition">
<label class="eval-caution"><i class="fa fa-exclamation-triangle yellow"></i> Caution</label>
</div>
</div>
[[ f.field_condition ]]
<hr>
</fieldset>
So basically, I have several sections, and each section has several fields. Each field has it's own radio button group (I am using the section and field ids to name the radio group). What I currently see is only the last field in each section actually shows the selected radio button. The other fields don't have any selection, even though the value for ng-model definitely does (I am showing the value of f.field_condition just to make sure there is a value).
For each field, I can see that the model is set. And if I select a value manually, I can see that the model changes, so it seems to me that the model is setup correctly. I just don't know why it won't initially show as selected for all rows but the last one.
I should also mention that if I save the form even with the missing radio button selections, the database is updated properly (it doesn't set the values to null, and if I manually change the selected value, it is updated in the db as well).
Does anyone have any ideas? Thanks!
EDIT
Here is a fiddle for this, although, it is working as expected in the fiddle. http://jsfiddle.net/dq8r196v/367/
I tried using the static data that I used in the fiddle, but I am still having the same problem. Does anyone know if this could be a CSS problem? The radio buttons are styled, and I didn't write the HTML or CSS.
UPDATE
I am still having this issue, so I built a new angular app and only used the code that is included in the fiddle that I have created. I am having the same problem with this new app, even though the same code works in the fiddle. I really don't understand what's happening here, but if anyone could shed some light, I would really appreciate it.
I have literally copied and pasted the code from my fiddle into a new angular app, and only the last group of radio buttons in each section is showing the value in the app.
Here is my complete code for the new angular app if someone else wants to try it out and see exactly what is happening: https://pastebin.com/qSR33yfM
I created the app on a single page for simplicity.
Here is the link to a pastebin with the exact json that I am using in my app: https://pastebin.com/utfVVQfT
I fixed the problem you're having by simply adding an array of objects ($scope.values) representing the different radio button options, and using an ng-repeat to create your radio buttons. See the following for the updated code: https://pastebin.com/s3hNzaXX
I know there are semantics around ng-repeat creating new $scopes, and imagine there is a conflict in scopes with your nested ng-repeats where it's binding to the radio buttons incorrectly and at a scope different than you want (the section level ng-repeat).
To confirm this suspicion, you could convert all of your interpolations in the code to use functions and console.log s and f at different points and confirm that field_condition is being set at a level you didn't intend.
Either way, it' best practice to create your radio buttons through data (and using ng-repeat), as is done with the $scope.values array, and a good side effect to doing this is not only can you update the different value options using data through AJAX or however you would like, but you won't have weird angular scoping issues as you're experiencing in your current code above.
I have Custom input component with validation with ngMessages,FormController and ng-required:
<div class="col-sm-9 col-xs-12">
<input
id="{{$ctrl.fieldName}}"
name="{{$ctrl.fieldName}}"
class="form-control"
type="text"
minlength="{{$ctrl.minLength}}"
maxlength="{{$ctrl.maxLength}}"
ng-required="{{$ctrl.isRequired === 'true'}}"
ng-model="$ctrl.value"
ng-change="$ctrl.form.$submitted = false;"
>
<div
ng-messages="$ctrl.form[$ctrl.fieldName].$error"
ng-if="$ctrl.form.$submitted"
>
<span class="help-block" ng-message="required">
Field is required
</span>
<span class="help-block" ng-message="minlength">
Minimum length of field: {{$ctrl.minLength}}
</span>
<span class="help-block" ng-message="maxlength">
Maximum length of field: {{$ctrl.maxLength}}
</span>
</div>
</div>
Which is used in this way:
<act-text-field
form="heroAddForm"
field-name="name"
min-length="3"
max-length="15"
is-required="true"
errors="$ctrl.errors.name"
ng-model="$ctrl.hero.name">
</act-text-field>
What I want to achieve is validation fires when user clicks submit button. And it works, validation fires also for required field name, but also for field description which is not required:
<act-text-field
form="heroAddForm"
field-name="description"
max-length="50"
is-required="false"
errors="$ctrl.errors.description"
ng-model="$ctrl.hero.description"
></act-text-field>
Also for this field validation messages are visible, although field description is valid, cause I add class has-error to invalid fields:
<div class="form-group"
ng-class="{'has-error': $ctrl.form.$submitted && (!$ctrl.form[$ctrl.fieldName].$valid)}"
>
<!-- rest of code -->
You can easily reproduced this wrong behaviour in my Plunker: Custom input demo app with validation states (I know it has other mistakes). I think ng-message="required" should not be visible, because field description is not required. I know I can add some ng-ifs to code to by-pass it, but I think I make a mistake somewhere which I can't see. Do you see where I made a mistake? Thank you in advance for every help.
I found a solution, again I forgot to include ngMessages. Without it, my code went crazy, I apologize for wasting your time :)
I have a ng-repeat that loops through an object and displays a list of strings and input fields, example below. I need to set up a real-time verification for these input fields. The input field should be equal to the barcode string. If a user types in a string that IS NOT equal to the barcode string than angular should prompt the user that it must equal the barcode string and clear the input field. Is this possible with angular? I’ve accomplished similar tasks with jQuery.. could I combine some jQuery and Angular to achieve this verification? I'm new with angular.js so any help is greatly appreciated.
HTML:
<div ng-repeat="(index, val) in barcodes.barcodes track by $index">
<div class="form-group row" ng-show="barcodes.barcodes[index]">
<label class="col-sm-3 form-control-label" style="margin-top: 5px"> {{ barcodes.adaptors[$index] }} </label>
<label class="col-sm-3 form-control-label" style="margin-top: 5px"> {{ barcodes.barcodes[index] }} </label>
<div class="col-sm-6">
<input type="email" class="form-control" placeholder="Barcode">
</div>
</div>
</div>
Example bars Object:
var bars = {
"adaptors": ["506-704", "505-703", "503-702", "508-701", "507-705", "502-706", "504-707", "501-708"],
"barcodes": ["11-11-1111","11-11-2222","11-11-3333","11-11-4444","X","X","X","X"];
}
if you want real time...watcher may be what you're looking for. But watcher is not efficient.
What would be best is to use the ng-change directive. This way, every time a user types, it will trigger the function passed to the ng-change directive. This can allow you to handle logic inside a function and react however you want.
https://docs.angularjs.org/api/ng/directive/ngChange
I use angular ng-messages to display validation messages
Consider the following code:
<ul ng-messages="formToValidate.fieldToValidate.$error" ng-messages-multiple>
<li ng-message="pattern">Invalid pattern</li>
<li ng-message="minlength, maxlength">Should contain no less than 7 and no more than 100 chars</li>
<li ng-message="!pattern && !minlength && !maxlength && onlyAfterAllOtherPassedValidation">
This validation message is shown only when all the other validations have passed and validation fails on onlyAfterAllOtherPassedValidation
</li>
</ul>
I want to show the last validation message only if all other validations have passed and validation fails on onlyAfterAllOtherPassedValidation.
And I do not know whether it's possible at all to pass complex condition to ng-message
Any suggestions as well as workarounds are welcomed as long as I still can use ng-messages
You could use ng-if on the element holding the message, eg
<li ng-if="!formToValidate.fieldToValidate.$error.required && !formToValidate.fieldToValidate.$error.minLength && !formToValidate.fieldToValidate.$error.maxLength" ng-message="onlyAfterAllOtherPassedValidation">
This validation message is shown only when all the other validations have passed and validation fails on onlyAfterAllOtherPassedValidation
</li>
The solution proposed by JonMac1374 of course work. But it is better to solve this problem once and for all. I advise you to pay attention to the directive use-form-error. It helps to build their own check.
Live example on jsfiddle.
<form name="ExampleForm">
<label>Password</label>
<input ng-model="password" name="password" minlength="2" pattern="^\d*$" required use-form-error="onlyAfterAllOtherPassedValidation" use-error-expression="!ExampleForm.password.$error.required && !ExampleForm.password.$error.minlength && !ExampleForm.password.$error.pattern"
/>
<pre>{{ExampleForm.password.$error|json}}</pre>
<div ng-messages="ExampleForm.password.$error" ng-messages-multiple="true" class="errors">
<div ng-message="required">
Your required is wrong
</div>
<div ng-message="pattern">
Your pattern is wrong
</div>
<div ng-message="minlength">
Your minlength is wrong
</div>
<div ng-message="onlyAfterAllOtherPassedValidation">
Your onlyAfterAllOtherPassedValidation
</div>
</div>
</form>