Display validation message with ng-messages based on multiple conditions - javascript

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>

Related

HTML required fields are not showing a message when it's not filled out

I have a big form for a website, with multiple required fields, and all of them are working perfectly, when i click submit on the form, the web page scroll to the field's location with an error message, except on two parts, the "Number of travelers" and the "Date of the trip".
This is the HTML for both of them:
<div class="sect-txt" style="margin-top:100px;" id="op">
<h1> Date of the trip </h1>
<div class="al">
<h1 style="font-family:Montserrat;font-size:14px;color:#161616;margin-bottom:5px;"> Check In </h1>
<input type="date" class="hide-replaced" data-date-size="1" placeholder="Check-in" name="checkin" required />
</div>
<div class="al">
<h1 style="font-family:Montserrat;font-size:14px;color:#161616;margin-bottom:5px;"> Check Out </h1>
<input type="date" class="hide-replaced" data-date-size="1" placeholder="Check-out" name="checkout" required />
</div>
<a href="#four">
<div class="btn-nxt" style="position:relative;top:137px;">
NEXT
</div>
</a>
</div>
<div class="sect-txt">
<h1> Number of travelers </h1>
<input type="number" class="f-2" placeholder="Adults" name="adults" required/>
<input type="number" class="f-3" placeholder="Children" name="childrens" required/>
<a href="#fif">
<div class="btn-nxt-b">
NEXT
</div>
</a>
</div>
And this is a link to the page in action: http://www.eliteware.co/92/form/
Your button is not focusable because you are trying to hide it when it has to receive focus again. Check the following link for more information about why this happens. Basically, you are hiding the object that is supposed to receive focus when validation is needed. If you don't want this to happen, you can probably do validation before hiding, or unhide the object if validation fails.
https://stackoverflow.com/a/28340579/616813
Also, do remember, if an error log exists, that is the first point to check if you receive an error. That is the whole point of error log, to give you a starting point to debug.
Or as Andreas said, "Fix the damn errors in the console... :)".
Edit:
Because it was killing me, I tried to reverse engineer your application. All it took was comparing the textbox that was working, and the one that was failing to find the problem. Really, that easy.
aria-required="true"
Your "Adults" and "Children" input fields have this property. You need required="true" instead.
Check your css and update that. And no, I have no idea why "aria=required" and "required" property behave differently. It is something new to learn for sure.

Angular2 / HTML validation stopped working

I've been writing a web application and i've got three different forms.
I've put some validation on them but it seems that after a recent update everything gets ignored.
Validation that still works:
-checks if input isn't empty
-Maxlength
Validation that stopped working:
-Patterns
-input type email ( This is the one that surprises me the most), it doesn't
check for an '#' anymore or any other checks it does if you put your input
type to email.
example code = `
<div class="form-group" [ngClass]="{ 'has-error': submitted && (!trainer.email || emailExists)}">
<label for="email">E-mail*</label>
<input [(ngModel)]="trainer.email" type="email" class="form-control" name="email" maxlength="50" placeholder="Enter e-mail adress" />
<div *ngIf="submitted && !trainer.email" class="help-block">E-mail adress is required</div>
<div *ngIf="submitted && emailExists" class="help-block">E-mail adress "{{emailInUse}}" is already in use</div>
</div>
`
I've removed everything from the html and put in just a single email input type and it still doesn't work. I guess it goes wrong somewhere else in my code but I don't know where to start looking. This example is for my trainer class but I have 2 other html files that also suddenly stopped working so that adds to my conclusion that the problem isn't in the HTML.
Is there any common bug that causes these kinds of problems?
Thanks

Angular Form Validation: $error.required set even when ng-required=false with custom input directive

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 :)

validating input fields using angular and jquery?

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.

AngularJS 1.3 - why is the form valid on load, for inputs with a minimum length?

I am just getting started with AngularJS and wish to disable the submit button of the form, if the form has any fields which are invalid.
I have a field called Title. It has a requirement that the minlength is 5. On load of the form, the form object provided by AngularJS reports that $invalid: false
<div ng-controller="NewPinCtrl as newPin">
<form role="form" name="formNewPin">
<div>
<label>Title</label>
<input ng-model="newPin.pin.title" ng-minlength="5" ng-maxlength="140" type="text" name="title" value="" placeholder="Title" />
<ul ng-messages="formNewPin.title.$error" ng-if="formNewPin.title.$dirty">
<li ng-message="required">This is required</li>
<li ng-message="minlength">Should be longer than 5 characters</li>
<li ng-message="maxlength">Should be shorter than 140 characters</li>
</ul>
</div>
</form>
</div>
And here is my button:
<button ng-click="newPin.savePin()" ng-disabled="formNewPin.$pristine || formNewPin.$invalid" type="button">Submit</button>
Fine I thought, I'll just disable the button if the form is $pristine: true. That solved my 'on load' issue...but when a user clears the field and goes back to blank, $invalid reports as false.
Why is this, when the field clearly has a minlength requirement? And, how can I get around it without checking each form field error individually?
Thanks!
EDIT: I might add, that I'm using this new ngMessages for 1.3
You have provided the message for required error, but you haven't marked the input as required. That's why it is evaluated as valid on first load.
After adding required attribute, you won't need using ng-if for ng-messages. The final solution should look like this:
<form name="formNewPin">
<label>Title</label>
<input ng-model="newPin.pin.title" required ng-minlength="5" ng-maxlength="140" type="text" name="title" value="" placeholder="Title">
<ul ng-messages="formNewPin.title.$error">
<li ng-message="required">This is required</li>
<li ng-message="minlength">Should be longer than 5 characters</li>
<li ng-message="maxlength">Should be shorter than 140 characters</li>
</ul>
<button ng-click="newPin.savePin()" ng-disabled="formNewPin.$invalid" type="button">Submit</button>
</form>
Plunker for this.

Categories