ng-maxlength not working - javascript

I have an Angular 4 Application. I am trying to add validation to form inputs, where inputs with numbers should not accept more than 4 digits. If more, it should invalid the form. I am using reactive forms. This is the code.
<input class="form-control form-control-amount no-z-index"
id="forNumber"
name="forNumber"
formControlName="forNumber"
ng-required="true"
type="number"
ng-maxlength="4"
[(ngModel)]="saveNumber"
[attr.disabled]="!condition? 'disabled': null "
#forNumber
>
<small class="alert alert-danger" *ngIf="!form.get('forNumber').valid">
Invalid input.
</small>
If I enter 11111 it should invalid the entry and should print above alert message; which is not happening.
Any idea what's going wrong here? Thanks.

First, you don't use a ngModel and a formControlName together. And I don't know about the ViewChild reference, and what you do with it, but if it's only to get the value, then you don't need it either.
Second, ng- is AngularJS, not Angular.
Third, you need to add a validator to you control.
<input class="form-control form-control-amount no-z-index"
id="forNumber"
name="forNumber"
formControlName="forNumber"
ng-required="true"
type="number"
maxlength="4"
[attr.disabled]="!condition? 'disabled': null "
>
Now, to add the validator, in your TS
constructor(private FB: FormBuilder) {
this.myForm = FB.group({
forNumber: ['', [Validators.maxLength(4)]]
});
}

Related

add dirty attribute to text and dropdownlist with [ngModelOptions]="{standalone: true}" in angular 8 (kendo)

I have a few dropdownlist tag that is binding dynamic data, so I need to use [ngModelOptions]="{standalone: true}". I know that using ngModelOption means ignoring the form attribute, is there any more that can add the dirty attribute to text or dropdownlist.
HTML file
<form #form="ngForm">
<div #ngFor="let item of [].constructor(details.length); let i = index>
<input [(ngModel)]="person[i].age" id="age" name="age" [ngModelOptions]="{standalone: true}"/>
<kendo-dropdownlist [data]="personName" [(ngModel)]="person[i].name" id="name" name="name" [ngModelOptions]="{standalone: true}"></kendo-dropdownlist>
</div>
<input [(ngModel)]="city" id="city" name="city" />
<button (click)="checkDirty()">CHECK DIRTY</button>
</form>
typescript file
#ViewChildren('form', {static: true})
public form: NgForm;
details = ["one","two"];
personName=["A","B","C"];
city="";
person = [{"age":"", "name":""},{"age":"", "name":""}];
checkDirty(){
console.log(this.form.dirty);
// when i type something in the city input, and click check dirty button, it return true
// however, if i type anything in age input or select any value in name and click check dirty button, it always return false.
}
I know that adding [ngModelOptions]="{standalone: true} basically means ignore the attribute in form. Is there any way that can add the dirty attribute manually for the dropdownlist name and input age?

angular reactive pattern for only numbers with + and #

I'm working on reactive form with postal code control it allows only + and # only with numbers. Max length for the controls is 10. I tried with following code even i enter the valid value it still shows the error.
ts
postalCode: ['', {
validators: [
Validators.required,
Validators.pattern('/^(?=.*[0-9])[+#()0-9]+$/')
],
updateOn: 'blur'
}],
View
<input type="text"
class="form-control"
id="postalCode"
formControlName="postalCode"
maxlength="10">
<div class="error-msg"
*ngIf="driverForm.controls.postalCode.hasError('pattern')">
<span class="red-star"> patter Error </span>
</div>
Remove quotes from regex
Instead of
'/^(?=.*[0-9])[+#()0-9]+$/'
Use without ' quotes
/^(?=.*[0-9])[+#()0-9]+$/

type number and pattern not showing error label

I want to have a field in which users can type only numbers 0-9. In case they type other characters like '.' or 'e' it has to show an error that only positive natural numbers are allowed. Form is used in Angular.
So I have here the html form:
<div class="col-xl-8">
<input formControlName="money" type="number" class="form-control">
<span class="error" *ngIf="money?.errors?.pattern"> Natural numbers </span>
</div>
while pattern is
this.money = new FormControl('', [Validators.required, Validators.pattern('^[1-9][0-9]*$')]);
The pattern is just fine it allows numbers from 0 till 9 and it doesn't allow decimals or '.' or 'e'.
So the problem is that since input is type number it allows '.' and 'e' even though the pattern doesn't allow it and I can't submit it, the error message is not showed since the html validater is based on the type number thing.
Yet, inputs such as these are allowed and the error label does not appear:
1.....2
......
eeee........
1.0.0.01.0
And so on.
So what should I do to show the error label when '.' or 'e' are typed?
Use ng-pattern directive directly?
<div class="col-xl-8">
<input formControlName="money"
type="number"
ng-pattern="^[1-9][0-9]*$')]"
class="form-control">
<span class="error" *ngIf="money?.errors?.pattern"> Natural numbers </span>
</div>
And tie validation to $valid of that input myForm.myInput.$valid
Use following code:
<div class="col-xl-8">
<input [formControl]="money"
type="number"
class="form-control">
<span class="error" *ngIf="money.dirty && money?.errors?.pattern"> Natural numbers </span>
</div>
In your ts file update regex ^[1-9][0-9]{1,3}
Hope it will help
In .ts file :
export class ReactiveFormExampleComponent{
reactiveForm: FormGroup;
constructor(private fb: FormBuilder) {
this.reactiveForm = fb.group({
money: ['', [Validators.required, Validators.pattern('^[1-9][0-9]*$')]]
});
}
onSubmit() {
alert("Form submitted");
}
}
html file
<form [formGroup]="reactiveForm" (ngSubmit)="onSubmit()" nonvalidate>
<div>
<label class="center-block">Money:
<input type="number" class="form-control" formControlName="money">
</label>
<span [hidden]="reactiveForm.controls.money.valid || reactiveForm.controls.money.pristine" class="errorMsg">Natural numbers only</span>
</div>
<button type="submit" [disabled]="reactiveForm.invalid" class="btn btn-success">Save</button>
</form>
NOTE : Don't forget to import 'ReactiveFormsModule' in NgModule.
Here is working plunker check it out here.

ng-change doesn't trigger on number input type

I am using angularJS, and I'm trying to get an error to pop up if the input value is not a number.
Number Value: <input type="number" ng-model="mydata.number" ng-change="checkNumber()" />
<p style="color:red" ng-show="numberError">
{{ numberError }}
</p>
And then inside $scope.checkNumber I check to see if it's NaN:
if(!$scope.mydata.number || isNaN($scope.mydata.number)) {
$scope.numberError = "This must be a number";
}
It appears that when I initially enter a string such as "fff" no error popups up, and we don't enter the checkNumber function, but if I enter "1fff" then it does enter the function and the error shows like it should.
If the input type is number and the initial character is not a number, does the ng-model not change?
What about using the Angular built-in validation, like this:
<form name="myForm">
Number Value:
<input type="number" ng-model="mydata.number" name="myNumber" />
<p style="color:red" ng-show="myForm.myNumber.$dirty && !myForm.myNumber.$valid">
{{ numberError }}
</p>
</form>

JQuery validate triggered every time the browser gets the focus

I am using jquery validation plugin to validate my form. I have one field that I don't want to validate but in some way it is validated anyway and I get the error message "Please enter no more than 5 characters."
The field that is validated is a type=file field and I use it together with the Fynework jQuery MultiForm plugin. It's not validated when I try to submit the form, only when I chose file that has a name longer than 5 characters (I think, short names work long doesn't).
I have tried adding the class .ignore to the field that is validated and added that the ignore rule to my validat(), not difference in behaviour.
What can the problem be?
Here is my validat() method, I also include the point at which I add that method:
function addNewTicketValidation(){
$("#newticketform").validate({
ignore: ".ignore",
errorContainer: "#messageBox1",
errorLabelContainer: "#messageBox1 ul",
wrapper: "li",
debug:true,
rules: {
title: "required",
description: "required"
},
messages: {
title: "Titel saknas",
description: "Beskrivning saknas"
}
});
}
$("#newticketmanu").live('click',function(event){
$("#adminarea").load("http://" + hostname + "/" + compdir + "/modules/core/newticket/newticket.php", function(){
$('#my_file_element').MultiFile();
addNewTicketValidation();
});
});
My form:
<form method="post" enctype="multipart/form-data" id="newticketform" class="MultiFile-intercepted" novalidate="novalidate">
<input type="hidden" value="2000000" name="MAX_FILE_SIZE">
<label for="title">Rubrik</label> <input type="text" name="title" id="title"><br><br>
<label for="description">Beskrivning</label> <textarea name="description" id="description" cols="50" rows="15"></textarea><br>
<div id="my_file_element_wrap" class="MultiFile-wrap"><input type="file" maxlength="5" name="file[]" id="my_file_element" class="multi ignore MultiFile-applied" value=""><div id="my_file_element_wrap_list" class="MultiFile-list"></div></div>
<div id="files_list"></div>
<input type="submit" value="Upload" name="upload">
</form>
What can the problem be and how to fix it?
Thanks!
Remove the maxlength="5" attribute from the file input. This is read by the validation plugin and added as a rule (line 812 here https://github.com/jzaefferer/jquery-validation/blob/1.9.0/jquery.validate.js). Checking the specifications (http://www.blooberry.com/indexdot/html/tagpages/i/inputfile.htm), max length still means character length even on a file input, so if you want to limit the user to 5 file uploads you'll need some other method of achieving this.

Categories

Resources