angular reactive pattern for only numbers with + and # - javascript

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]+$/

Related

Password Validation error in Angular Reactive Form Validator

Using Angular Reactive Form to validate password which as to match Password with atleast :
|*> 1 lowercase
|*> 1 uppercase
|*> 1 numeric
|*> 8 char longer
Using Reg Exp :
"^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})"
Html Code :
<form [formGroup]="NamFomNgs">
<label>Email :
<input type="email" name="MylHtm" formControlName="MylNgs">
</label><br>
<div class="ErrMsgCls" *ngIf="(NamFomNgs.controls['MylNgs'].touched || NamFomNgs.controls['MylNgs'].dirty) &&
!NamFomNgs.controls['MylNgs'].valid">
<span *ngIf="NamFomNgs.controls['MylNgs'].errors.required">This field is required</span>
<span *ngIf="NamFomNgs.controls['MylNgs'].errors.email">Enter valid email</span>
</div><br>
<label>Password :
<input type="text" name="PwdHtm" formControlName="PwdNgs">
</label><br>
<div class="ErrMsgCls" *ngIf="(NamFomNgs.controls['PwdNgs'].touched || NamFomNgs.controls['PwdNgs'].dirty) &&
!NamFomNgs.controls['PwdNgs'].valid">
<span *ngIf="NamFomNgs.controls['PwdNgs'].errors.required">This field is required</span>
<span *ngIf="NamFomNgs.controls['PwdNgs'].errors.pattern">Enter valid password</span>
</div><br>
<button [disabled]="!NamFomNgs.valid">Submit</button>
</form>
TypeScript Code :
NamFomNgs:FormGroup;
constructor(private NavPkjVaj: ActivatedRoute, private HtpCncMgrVaj: HttpClient,private FomNgsPkjVaj: FormBuilder){
this.NamFomNgs = FomNgsPkjVaj.group(
{
MylNgs:[null,Validators.compose([
Validators.required,
Validators.email ])],
PwdNgs:[null,Validators.compose([
Validators.required,
Validators.pattern("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})")])]
});
}
Screen Shot of Output :
When I try with https://regex101.com/
The same reg exp shows valid for the requirments. But its invalid in Angular. Kindly help me with right way and to resolve this.
You have to capture something in your regex, you're only using positive look-ahead groups. Just change the length part like this :
"^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,}"

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-maxlength not working

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)]]
});
}

Regular expression not working properly.in javascript

I am using the following code:
this.totalCars = kb.observable(model, 'totalCars').extend({required:true,min:1, max: 7,
pattern : {
params: /^[\d]*$/,
message: 'Enter Valid Integer Number'
}
});
and in the UI am using:
<div class="col-md-8">
<input required
type="number"
id="numberofcars"
title="Number of cars"
placeholder="Number of cars Offered"
autocomplete="off"
data-bind="value: totalCars"
min="1" maxlength="1"
class="form-control c-square c-theme input-sm">
</div>
It's accepting + and e,E
Note: it doesn't accept e+E characters. how to restrict here
I suggest replacing your custom regex with the built in / native rule for numbers using number: true:
var model = null;
var vm = {
totalCars: ko.observable(model, 'totalCars').extend({
required: true,
min: 1,
max: 7,
number: true
})
};
vm.errors = ko.validation.group(vm);
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.min.js"></script>
<input required
type="number"
placeholder="Number of cars Offered"
data-bind="textInput: totalCars"
min="1"
maxlength="1" >
<hr>
Debug info: <pre data-bind="text: ko.toJSON($root)"></pre>
PS. I also did something similar to what commenters suggested, using the textInput binding that makes sure the changes are pushed to the view model on key presses, not on blurring the input field. But that's just a minor change to make the example clearer.
The relevant source from ko-validation has this implementation for that native rule (slightly reformatted for SO legibility):
return ko.validation.utils.isEmptyVal(value)
|| (validate && /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(value));
As you can see this regex is quite elaborate, and probably well-tested. It works as I expected at any rate.

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>

Categories

Resources