5

I am using NGX-Schema-Form https://github.com/makinacorpus/ngx-schema-form to render form fields based on a json object.

My question is: How to add custom validation error messages to my schema and also how to display them properly on the ui (Bootstrap 4.1 based).

Here is an example of the standard schema format:

Note: Pattern, minLength, maxLength

mySchema = {
"properties": {
    "cellphoneNumber": {
        "type": "string",
        "title": "Cellphone number",
        "placeholder": "e.g. 082 320 2121",
        "widget": {
            "id": "string"
        },
        "pattern": "^\\d{10}$",
        "minLength": 5,
        "maxLength": 12
    }
}

But what i would like to do:

mySchema = {
"properties": {
    "cellphoneNumber": {
        "type": "string",
        "title": "Cellphone number",
        "placeholder": "e.g. 082 320 2121",
        "widget": {
            "id": "string"
        },
        pattern: {
            value: '^\\d{10}$',
            message: 'Cellphone number must be 10 digits'
        },
        minLength: {
            value: '5',
            message: 'Please enter at least 5 characters'
        }
        maxLength: {
            value: '14',
            message: 'Please enter no more than least 14 characters'
        }
    }
}

Any ideas?

And then also how to override the standard string widget to show this error if the form and field is ng-dirty and ng-touched.

Rough example:

<div class="error mt-2" *ngIf="control.errors && control.pristine == false || control.touched == true">
  <div *ngFor="let err of control.errors">
    {{ err.message }}
  </div>
</div>

Im am looking for a solid solution please for enterprise level implementation.

Shubham Verma
  • 8,783
  • 6
  • 58
  • 79
  • Is there anything you have tried in order to achieve this? – Michael Doye Jun 25 '18 at 11:26
  • 1
    Yes I have tried to display the appropriate message like in my Rough Example but the errors returned is the standard angular pattern, minLength, maxLength errors messages.: ```[ { "code": "PATTERN", "params": [ "^\\d{10}$", "" ], "message": "String does not match pattern ^\\d{10}$: ", "path": "#/" },``` – Jean-paul de Beer Jun 25 '18 at 11:33
  • 1
    I have created my own stringWidget that overrides the standard stringWidget but I am unsure how to resolve the schemas error validation and message to this overridden template. – Jean-paul de Beer Jun 25 '18 at 11:39
  • @Jean-pauldeBeer Have you managed to resolve this? – toms Feb 03 '21 at 13:55

1 Answers1

-2

You can use FormsModule, ReactiveFormsModule into your app to do so.

Please follow to do so.

Import FormsModule, ReactiveFormsModule into your module.ts file.

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { emailRegexp, passwordRegexp } from '../../constants'; // if you have any email regex for validation otherwise remove it.

Add into @NgModule:

@NgModule({
  imports: [
    BrowserModule,
    ReactiveFormsModule
  ],
  declarations: [
        AppComponent
  ],
})
export class AppModule {
}

Now goto your component where your form needs to valoidate:

import { FormBuilder, FormGroup, Validators, NgForm } from '@angular/forms';

Initialize in your constructor:

   constructor(
        private formBuilder: FormBuilder,
    ) { }

Create your form validator: ( I am using for login purpose ):

    // login form validations
    this.loginForm = this.formBuilder.group({
        email: ['', Validators.compose([Validators.required)])], // If you don't have any email regex. otherwise write this=>             email: ['', Validators.compose([Validators.required, Validators.pattern(emailRegexp)])],

        password: ['', Validators.compose([Validators.required, Validators.minLength(8)])]
    });
}

Now create your form ( In HTML ) like this:

    <form [formGroup]="loginForm" (ngSubmit)="loginForm.valid && login()" novalidate>
              <div *ngIf="loginError" class="form-group">
                  <div class="">
                    <p class="loginError">Incorrect Email/Password </p>
                  </div>

              <input type="email"  formControlName="email">

            <p *ngIf="loginForm.controls.email.touched && loginForm.controls.email.errors && loginForm.controls.email.errors.pattern"
              class="error-message">
              Invalid Email </p>

            <p *ngIf=" loginForm.controls.email.touched && loginForm.controls.email.errors && loginForm.controls.email.errors.required && !loginForm.controls.email.errors.pattern"
              class="error-message">
              Email is required </p>
          </div>

      <div class="form-group row">
        <div class="col-12">
          <input autocomplete="off" type="password" (focus)="focusFunction()" placeholder="Password" formControlName="password" class="form-control">
        </div>
        <div *ngIf="loginForm.controls.password.touched">
          <p *ngIf="loginForm.controls.password.errors && loginForm.controls.password.errors.required " class="error-message">Password is required </p>
          <p *ngIf=" loginForm.controls.password.errors && loginForm.controls.password.errors.minlength" class="error-message"> Min. 8 characters required.</p>
        </div>
      </div>

      <div class="form-group row">
        <div class="col-12">
          <button [disabled]="!loginForm.valid" type="submit" >
          <div  class="sign-in">Sign in</div>
          </button>
        </div>
      </div>
</form>
Shubham Verma
  • 8,783
  • 6
  • 58
  • 79
  • 3
    Thanks for this but this is just standard forms with validation (which I know how to do) but does not relate to my question specifically using NGX-FROM-SCHEMA generating the form dynamically from json and overriding ngx-schema-form string widget. – Jean-paul de Beer Jun 25 '18 at 12:51