A good form validation example?


#1

Hello i’m new on Ionic 3 and I search a good form validation example thats works

it’s been a while since I’m looking for on the internet but I find many solutions that do not work and are so complicated…

could someone share his code or a good tutorial for form valisation email and password ?

Thank’s in advance


Cannot read property 'hasError' of null
#2

#3

Thank’s.

It work with Ionic 3.9.2 and Angular 5 ?


#4

I haven’t tested it but looking at the changelogs of ionic and angular there shouldn’t be any problems.


#5

If possible, I would like a tutorial or a functional and up-to-date example but I already had a lot of mistakes


#6

@joshmorony Maybe that’s a good time for you to update that particular tutorial. :wink:


#7

No one to share his beautiful code? :face_with_raised_eyebrow:


#8

Here’s the structure I use. It’s not all of the code, but it gives you the idea.

Code:

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

export class MyPage {

    form : FormGroup;

    // Validation error messages that will be displayed for each form field with errors.
    validation_messages = {
        'myField': [
    		{ type: 'pattern', message: 'Please enter a number like 12345678/00.' }
    	]
    }

    constructor(public formBuilder: FormBuilder) {
        // Create the form and define fields and validators.
        this.form = this.formBuilder.group({
            myField: ['', Validators.pattern('[0-9]{8}/[0-9]{2}')]
        });

        // Initial value for the field.
        this.form.get('myField').setValue('11223344/55');
    }

    /*
     * Save form values.
     */
    save() {
        if (this.form.valid) {
            // Save your values, using this.form.get('myField').value;
        }
    }

Template:

    <form novalidate [formGroup]="form">

          <ion-item>
              <ion-label stacked>My Field Label</ion-label>
              <ion-input formControlName="myField"></ion-input>
          </ion-item>
          <div>
                <ng-container *ngFor="let validation of validation_messages.myField" >
              		<div *ngIf="form.get('myField').hasError(validation.type)">
              			<p>{{validation.message}}</p>
               		</div>
               	</ng-container>
          </div>

    </form>


A working good form validation example
#9

This my coding . I hope it will work fine for you

My signup.ts

//import this

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

export class SignupPage implements OnInit {
  signupform: FormGroup;
  userData = { "username": "", "password": "", "email": "", "name": "" };

  constructor() {
  }

  ngOnInit() {
    let EMAILPATTERN = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
    this.signupform = new FormGroup({
      username: new FormControl('', [Validators.required, Validators.pattern('[a-zA-Z ]*'), Validators.minLength(4), Validators.maxLength(10)]),
      password: new FormControl('', [Validators.required, Validators.minLength(6), Validators.maxLength(12)]),
      name: new FormControl('', [Validators.required, Validators.pattern('[a-zA-Z ]*'), Validators.minLength(4), Validators.maxLength(30)]),
      email: new FormControl('', [Validators.required, Validators.pattern(EMAILPATTERN)]),
    });
  }

And my html like this:

<ion-content padding>
  <ion-list>
    <form novalidate (ngSubmit)="signup()" [formGroup]="signupform">
      <ion-item>
        <ion-label floating>Name </ion-label>
        <ion-input type="text" [(ngModel)]="userData.name" formControlName="name" [class.error1]="!signupform.controls.name.valid && signupform.controls.name.dirty"></ion-input>
      </ion-item>
      <ion-item no-lines *ngIf="( signupform.get('name').hasError('minlength') || signupform.get('name').hasError('maxlength') ||signupform.get('name').hasError('pattern') ||signupform.get('name').hasError('required') ) && signupform.get('name').touched">
        <div class="error" *ngIf="signupform.get('name').hasError('required') && signupform.get('name').touched">
          Please input your name
        </div>
        <div class="error" *ngIf="signupform.get('name').hasError('minlength') && signupform.get('name').touched">
          Minimum 4 characters
        </div>
        <div class="error" *ngIf="signupform.get('name').hasError('maxlength') && signupform.get('name').touched">
          Maximum 30 characters
        </div>
        <div class="error" *ngIf="signupform.get('name').hasError('pattern') && signupform.get('name').touched">
          Just use alphabet character
        </div>
      </ion-item>

      <ion-item>
        <ion-label floating>Email</ion-label>
        <ion-input type="text" [(ngModel)]="userData.email" formControlName="email" [class.error1]="!signupform.controls.email.valid && signupform.controls.email.dirty"></ion-input>
      </ion-item>
      <ion-item no-lines *ngIf="( signupform.get('email').hasError('minlength') || signupform.get('email').hasError('pattern') ||signupform.get('email').hasError('required') ) && signupform.get('email').touched">
        <div class="error" *ngIf="signupform.get('email').hasError('required') && signupform.get('email').touched">
          Please input your email
        </div>
        <div class="error" *ngIf="signupform.get('email').hasError('pattern') && signupform.get('email').touched">
          Email address invalid
        </div>
      </ion-item>
      <ion-item>
        <ion-label floating>Username</ion-label>
        <ion-input type="text" [(ngModel)]="userData.username" formControlName="username" [class.error1]="!signupform.controls.username.valid && signupform.controls.username.dirty"></ion-input>
      </ion-item>

      <ion-item no-lines *ngIf="( signupform.get('username').hasError('minlength') || signupform.get('username').hasError('maxlength') ||signupform.get('username').hasError('pattern') ||signupform.get('username').hasError('required') ) && signupform.get('username').touched">
        <div class="error" *ngIf="signupform.get('username').hasError('required') && signupform.get('username').touched">
          Please input your username
        </div>
        <div class="error" *ngIf="signupform.get('username').hasError('minlength') && signupform.get('username').touched">
          Minimum 4 characters
        </div>
        <div class="error" *ngIf="signupform.get('username').hasError('maxlength') && signupform.get('username').touched">
          Maximum 10 characters
        </div>
        <div class="error" *ngIf="signupform.get('username').hasError('pattern') && signupform.get('username').touched">
          Just use alphabet character
        </div>
      </ion-item>
      <ion-item>
        <ion-label floating>Password</ion-label>
        <ion-input type="password" [(ngModel)]="userData.password" formControlName="password" [class.error1]="!signupform.controls.password.valid && signupform.controls.password.dirty"></ion-input>
      </ion-item>

      <ion-item no-lines *ngIf="( signupform.get('password').hasError('minlength') || signupform.get('password').hasError('maxlength') ||signupform.get('password').hasError('required') ) && signupform.get('password').touched">
        <div class="error" *ngIf="signupform.get('password').hasError('required') && signupform.get('password').touched">
          Please input your password
        </div>
        <div class="error" *ngIf="signupform.get('password').hasError('minlength') && signupform.get('password').touched">
          Minimum 6 characters
        </div>
        <div class="error" *ngIf="signupform.get('password').hasError('maxlength') && signupform.get('password').touched">
          Maximum 12 characters
        </div>
      </ion-item>
      <button type="submit" ion-button block color="primary" [disabled]="signupform.invalid">SIGNUP</button>
    </form>
  </ion-list>
</ion-content>
<style type="text/css">
  .error {
    color: rgb(223, 62, 62);
    font-size: 11px;
  }

  .error1 {
    color: rgb(75, 75, 75);
    border-bottom: 1px solid #ff0000;
  }

#10

Thank you very much @buchori it work like a charm :grinning:


#11

Its good, I hope it work for all…


#12

This one is updated for Ionic 3 and Angular 4


#13

Working with my Ionic 2 app. Thank you!


#14

See: https://robferguson.org/blog/2017/11/19/ionic-3-and-forms/


Cannot read property 'hasError' of null
#15

Hello, I’m getting ERROR TypeError: Cannot read property ‘get’ of undefined
any solution ? thanks


#16

You should check https://ionicthemes.com/tutorials/about/forms-and-validation-in-ionic it has lots of validation examples in ionic 3


#17

Have you fixed that… Please let me know whats-app: +94779279206


#18

Hello, I’m getting ERROR TypeError: Cannot read property ‘get’ of undefined
any solution ? thanks


#19

I got error like

Error: Uncaught (in promise): Error:
ngModel cannot be used to register form controls with a parent formGroup directive. Try using
formGroup’s partner directive “formControlName” instead. Example:

<div [formGroup]="myGroup">
  <input formControlName="firstName">
</div>

In your class:

this.myGroup = new FormGroup({
   firstName: new FormControl()
});

  Or, if you'd like to avoid registering this form control, indicate that it's standalone in ngModelOptions:

  Example:

  
<div [formGroup]="myGroup">
   <input formControlName="firstName">
   <input [(ngModel)]="showMoreControls" [ngModelOptions]="{standalone: true}">
</div>

Error:
ngModel cannot be used to register form controls with a parent formGroup directive. Try using
formGroup’s partner directive “formControlName” instead. Example:

<div [formGroup]="myGroup">
  <input formControlName="firstName">
</div>

In your class:

this.myGroup = new FormGroup({
   firstName: new FormControl()
});

  Or, if you'd like to avoid registering this form control, indicate that it's standalone in ngModelOptions:

  Example:

  
<div [formGroup]="myGroup">
   <input formControlName="firstName">
   <input [(ngModel)]="showMoreControls" [ngModelOptions]="{standalone: true}">
</div>

at Function.TemplateDrivenErrors.modelParentException (http://localhost:8100/build/vendor.js:30983:15)
at NgModel._checkParentType (http://localhost:8100/build/vendor.js:31341:34)
at NgModel._checkForErrors (http://localhost:8100/build/vendor.js:31325:18)
at NgModel.ngOnChanges (http://localhost:8100/build/vendor.js:31209:14)
at checkAndUpdateDirectiveInline (http://localhost:8100/build/vendor.js:12781:19)
at checkAndUpdateNodeInline (http://localhost:8100/build/vendor.js:14309:20)
at checkAndUpdateNode (http://localhost:8100/build/vendor.js:14252:16)
at debugCheckAndUpdateNode (http://localhost:8100/build/vendor.js:15145:76)
at debugCheckDirectivesFn (http://localhost:8100/build/vendor.js:15086:13)
at Object.eval [as updateDirectives] (ng:///AppModule/RegistrationPage.ngfactory.js:278:5)

at Function.TemplateDrivenErrors.modelParentException (http://localhost:8100/build/vendor.js:30983:15)
at NgModel._checkParentType (http://localhost:8100/build/vendor.js:31341:34)
at NgModel._checkForErrors (http://localhost:8100/build/vendor.js:31325:18)
at NgModel.ngOnChanges (http://localhost:8100/build/vendor.js:31209:14)
at checkAndUpdateDirectiveInline (http://localhost:8100/build/vendor.js:12781:19)
at checkAndUpdateNodeInline (http://localhost:8100/build/vendor.js:14309:20)
at checkAndUpdateNode (http://localhost:8100/build/vendor.js:14252:16)
at debugCheckAndUpdateNode (http://localhost:8100/build/vendor.js:15145:76)
at debugCheckDirectivesFn (http://localhost:8100/build/vendor.js:15086:13)
at Object.eval [as updateDirectives] (ng:///AppModule/RegistrationPage.ngfactory.js:278:5)
at c (http://localhost:8100/build/polyfills.js:3:19752)
at Object.reject (http://localhost:8100/build/polyfills.js:3:19174)
at NavControllerBase._fireError (http://localhost:8100/build/vendor.js:51705:16)
at NavControllerBase._failed (http://localhost:8100/build/vendor.js:51698:14)
at http://localhost:8100/build/vendor.js:51745:59
at t.invoke (http://localhost:8100/build/polyfills.js:3:14976)
at Object.onInvoke (http://localhost:8100/build/vendor.js:5134:33)
at t.invoke (http://localhost:8100/build/polyfills.js:3:14916)
at r.run (http://localhost:8100/build/polyfills.js:3:10143)
at http://localhost:8100/build/polyfills.js:3:20242

defaultErrorLogger @ core.js:1449
ErrorHandler.handleError @ core.js:1510
IonicErrorHandler.handleError @ ionic-error-handler.js:61
next @ core.js:5508
schedulerFn @ core.js:4342
SafeSubscriber.__tryOrUnsub @ Subscriber.js:242
SafeSubscriber.next @ Subscriber.js:189
Subscriber._next @ Subscriber.js:129
Subscriber.next @ Subscriber.js:93
Subject.next @ Subject.js:55
EventEmitter.emit @ core.js:4322
(anonymous) @ core.js:4782
t.invoke @ polyfills.js:3
r.run @ polyfills.js:3
NgZone.runOutsideAngular @ core.js:4708
onHandleError @ core.js:4782
t.handleError @ polyfills.js:3
r.runGuarded @ polyfills.js:3
(anonymous) @ polyfills.js:3
n.microtaskDrainDone @ polyfills.js:3
o @ polyfills.js:3
e.invokeTask @ polyfills.js:3
p @ polyfills.js:2
v @ polyfills.js:2


#20

hii i need to know how to validate chekboxes and radio input in ionic v3 i searched so many solutions but i didn’t find a good response