How to validate in a reactive form of angular data entry so that they are only numbers?

1

I have a reactive form in Angular 5.2.0 . Configure the validations; nid, name, email, address. All work well, they show the right message in each case. But in the case of a (N.I.D.), which I ask accept only numbers, the error message appears whether they are letters, numbers or special characters. I used it without the compose, that single validation. I have changed the regular expression in the pattern several times. I've even used the pattern in the input, but without success. The message continues to appear: " Your NID must contain only numbers "

The html:

<div class="form-group">
    <label class="col-md-4">NID</label>
    <input type="text" class="form-control" formControlName="nid" #nid pattern="[1-9]\d{6,10}" />
</div>
<div *ngIf="userForm.controls['nid'].invalid && (userForm.controls['nid'].dirty || userForm.controls['nid'].touched)" class="text-light badge-danger my-2 py-2">
    <div *ngFor="let validation of user_validation_messages.nid" >
        <div style="font-size: smaller !important;" *ngIf="userForm.get('nid').hasError(validation.type) && (userForm.get('nid').dirty || userForm.get('nid').touched)">
            {{validation.message}}
        </div>
    </div>
</div>

The typescript

/* Los mensajes */
user_validation_messages = {
    'nid': [
        { type: 'required', message: 'NID is required' },
        { type: 'minlength', message: 'NID must be at least 6 characters long' },
        { type: 'maxlength', message: 'NID cannot be more than 10 characters long' },
        { type: 'pattern', message: 'Your NID must contain only numbers' }
    ],

/* La validacion */
this.userForm = this.fb.group({
     nid: [null, Validators.compose([
        Validators.required,
        Validators.minLength(6),
        Validators.maxLength(10),
        Validators.pattern('/^[1-9]\d{6,10}$/')
    ])],

1 Edition

A sample of the result:

    
asked by PulidoVPE 09.08.2018 в 15:39
source

2 answers

0

The problem is that you are mixing quotes ' with delimiters / . Either use quotation marks or use delimiters.

Also, with [1-9] you are not taking into account the 0 .

A simpler regular expression is ^\d+$ . With \d you take all the digits, and you do not take the lengths because anyway you are already validating the minimum and the maximum with the other validators and they give you the corresponding messages.

    
answered by 09.08.2018 / 19:53
source
0

Thanks to the user Julio for helping me with your suggestions.

In this case; using pattern (/.*/) without the quotes the other validations have worked and the error message has not appeared. Whether I type numbers or letters.

I have tried the appropriate regular expression pattern (/ ^ [1-9] \ d {6,10} $ /) also without the quotes and it has finally worked. It seems that was the whole problem.

Thanks for the help.

    
answered by 09.08.2018 в 19:49