模式不匹配少于或多于10个数字

时间:2018-01-14 18:21:57

标签: angular typescript

我创建的代码只匹配10个以上的数字或者没有,但是如果给出的输入是5位数呢?如果它小于或大于10位,我想显示错误。 代码:

<div class="form-group">
    <label for="email">Mobile Number</label>
    <input type="number" name="mobileNumber" [(ngModel)]="mobile_no"  ngPattern=" /^[0-9]{10}$/;" class="form-control" id="mobileNumber" minlength="10" maxlength="10" required #mobileNumber="ngModel">
    <div *ngIf="mobileNumber.invalid && (mobileNumber.dirty || mobileNumber.touched)" class="alert alert-danger">
        <div *ngIf="mobileNumber.errors.required || mobileNumber.errors.minlength || mobileNumber.errors.maxlength ||mobileNumber.errors.ngPattern">
        Mobile number is required and it cannot be more than or less than 10 characters. Please enter a valid mobile number.
        </div>
    </div>
</div>

1 个答案:

答案 0 :(得分:0)

尝试这样做:

 <div class="form-group">
        <label for="email">Mobile Number</label>
        <input type="number" name="mobileNumber" [(ngModel)]="mobile_no"  ngPattern=" /^[0-9]{10}$/;" class="form-control" id="mobileNumber" minlength="10" maxlength="10" required #mobileNumber="ngModel">
        <div *ngIf="mobileNumber.invalid && (mobileNumber.dirty || mobileNumber.touched)" class="alert alert-danger">
            <div *ngIf="mobileNumber.errors.required || mobileNumber.errors.minlength || mobileNumber.errors.maxlength ||mobileNumber.errors.ngPattern; else #error">
            Mobile number is required and it cannot be more than or less than 10 characters. Please enter a valid mobile number.
            </div>
            <ng-template #error>You should put 10 digits at least</ng-template>
        </div>
    </div>