San*_*nde 30 forms validation angular angular4-forms
我正在尝试开发一个联系表单,我希望用户输入长度为10-12的电话号码.
值得注意的是,相同的验证工作在Message字段,它唯一的数字字段给我带来了麻烦.
我有以下代码:
HTML:
<form [formGroup]="myForm" (ngSubmit)="myFormSubmit()">
<input type="number" formControlName="phone" placeholder="Phone Number">
<input type="text" formControlName="message" placeholder="Message">
<button class="button" type="submit" [disabled]="!myForm.valid">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)
TS:
this.myForm = this.formBuilder.group({
phone: ['', [Validators.required, Validators.minLength(10), Validators.maxLength(12)]],
message: ['', [Validators.required, Validators.minLength(10), Validators.maxLength(100)]]
});`
Run Code Online (Sandbox Code Playgroud)
San*_*nde 14
更新1:
phone: ['', [Validators.required, Validators.min(10000000000), Validators.max(999999999999)]],
Run Code Online (Sandbox Code Playgroud)
使用它像跟随和完美工作:
phone: ['', [Validators.required, customValidationService.checkLimit(10000000000,999999999999)]],
Run Code Online (Sandbox Code Playgroud)
customValidationService:
import { AbstractControl, ValidatorFn } from '@angular/forms';
export class customValidationService {
static checkLimit(min: number, max: number): ValidatorFn {
return (c: AbstractControl): { [key: string]: boolean } | null => {
if (c.value && (isNaN(c.value) || c.value < min || c.value > max)) {
return { 'range': true };
}
return null;
};
}
}
Run Code Online (Sandbox Code Playgroud)
试试这个工作示例代码:
component.html
<div class="container">
<form [formGroup]="myForm"
(ngFormSubmit)="registerUser(myForm.value)" novalidate>
<div class="form-group" [ngClass]="{'has-error':!myForm.controls['phone'].valid}">
<label for="phone">Email</label>
<input type="phone" formControlName="phone" placeholder="Enter Phone"
class="form-control">
<p class="alert alert-danger" *ngIf="myForm.controls['phone'].hasError('minlength')">
Your phone must be at least 5 characters long.
</p>
<p class="alert alert-danger" *ngIf="myForm.controls['phone'].hasError('maxlength')">
Your phone cannot exceed 10 characters.
</p>
<p class="alert alert-danger" *ngIf="myForm.controls['phone'].hasError('required') && myForm.controls['phone'].dirty">
phone is required
</p>
</div>
<div class="form-group text-center">
<button type="submit" class="btn btn-primary" [disabled]="!myForm.valid">Submit</button>
</div>
</form>
</div>
Run Code Online (Sandbox Code Playgroud)
component.ts
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
export class AppComponent implements OnInit {
myForm: any;
constructor(
private formBuilder: FormBuilder
) {}
ngOnInit() {
this.myForm = this.formBuilder.group({
phone: [null, Validators.compose([Validators.required, Validators.minLength(5), Validators.maxLength(10)])]
});
}
}
Run Code Online (Sandbox Code Playgroud)
我有个窍门,那就是100%工作。
定义类型为“文本”而不是“数字”的输入。
例如:
<input placeholder="OTP" formControlName="OtpUserInput" type="text">
然后使用作为验证的一部分的模式。
喜欢 :
this.ValidOtpForm = this.formbuilder.group({
OtpUserInput: new FormControl(
{ value:'', disabled: false },
[
Validators.required,
**Validators.minLength(6),
Validators.pattern('[0-9]*')**
]),
});
Run Code Online (Sandbox Code Playgroud)
这意味着我们定义了适合最小长度的输入类型文本,还定义了数值的pattern(validation),以便我们可以同时实现这两个验证。
剩余代码:
<mat-error *ngIf="RegistrationForm.controls['Password'].hasError('minlength')">Use 6 or more characters with a mix of letters</mat-error>
<mat-error *ngIf="ValidOtpForm.controls['OtpUserInput'].hasError('pattern')">Please enter numeric value.</mat-error>
Run Code Online (Sandbox Code Playgroud)
你不应该在这里使用长度,对于 min 和 max 使用这样的自定义验证器,
var numberControl = new FormControl("", CustomValidators.number({min: 10000000000, max: 999999999999 }))
Run Code Online (Sandbox Code Playgroud)
这个技巧会有帮助
在.html文件中
<input type="text" (keyup)="onKeyUp($event)" formControlName="phone" placeholder="Phone Number">
Run Code Online (Sandbox Code Playgroud)
在.ts文件中
下面的代码限制字符串字符
public onKeyUp(event: any) {
const NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
let newValue = event.target.value;
let regExp = new RegExp(NUMBER_REGEXP);
if (!regExp.test(newValue)) {
event.target.value = newValue.slice(0, -1);
}
}
Run Code Online (Sandbox Code Playgroud)
和其他验证
phone: ['', Validators.compose([
Validators.required,
Validators.pattern('^[0-9]{0,30}$')])
])],
Run Code Online (Sandbox Code Playgroud)
上述模式代码最多允许 30 位数字。如果你想要至少两位数,你可以这样做
Validators.pattern('^[0-9]{2,30}$')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
60305 次 |
| 最近记录: |