Search results

Perform custom validation using FormValidator in Angular NumericTextBox component

This section explains how to perform custom validation on the NumericTextBox using FormValidator. The NumericTextBox will be validated when the value changes or the user clicks the submit button. Validation can be performed by adding custom validation in the rules collection of the FormValidator.

Source
Preview
app.component.ts
app.module.ts
main.ts
index.html
index.css
import { Component, ViewChild } from '@angular/core';
import { NumericTextBoxComponent  } from '@syncfusion/ej2-angular-inputs';
import { FormValidator, FormValidatorModel } from '@syncfusion/ej2-inputs';

@Component({
    selector: 'app-root',
    // Initializes the NumericTextBox
    //Renders submit button for validating the NumericTextBox
    template: `
    <form #formElement class="form-horizontal">
        <div class="form-group">
            <div class="col-sm-6">
                <ejs-numerictextbox #numeric="" id="numeric"  [strictMode]='false'  min='10' max='100' name="numeric" placeholder= 'NumericTextbox' floatLabelType= 'Always'  (created)="onCreate($event)" (change)= "onChange($event)"></ejs-numerictextbox>
            </div>
                <button type="button" id="submit_btn" (click)="btnClick()" style="margin-top: 10px">Submit</button>
        </div>
    </form>
    `
})

export class AppComponent {
    @ViewChild('formElement') element;
    @ViewChild('numeric') numeric: NumericTextBoxComponent;
    public formObject: FormValidator;
    ngAfterViewInit() {
        let customFn: (args: { [key: string]: string }) => boolean = (args: { [key: string]: string }) => {
            if(numeric.value>=10 && numeric.value<=100) {
                return true;
            }
            else {
                return false;
            }
        };
        // sets required property in the FormValidator rules collection
        let options: FormValidatorModel = {
            rules: {
               'numericRange': { required: [true, "Number is required"] },
            },
            //to place the error message in custom position
            customPlacement: (inputElement: HTMLElement, errorElement: HTMLElement) => {
                inputElement.parentNode.parentNode.parentNode.appendChild(errorElement);
            }
        };
        this.formObject = new FormValidator(this.element.nativeElement, options);

        this.formObject.addRules('numericRange', { range: [customFn, "Please enter a number between 10 to 100"] });
        var proxy = this;
    }
    // validates NumericTextBox while value changes
    public onChange(args){
        if (numeric.value != null)
            this.formObject.validate("numericRange");
    }
    public onCreate(){
          document.getElementById("numeric").setAttribute("name", "numericRange");
    }
    public btnClick(): void {
        // validates the NumericTextBox
        this.formObject.validate("numericRange");
        // checks for incomplete value and alerts the form
        let ele: HTMLInputElement = <HTMLInputElement>document.getElementById('numeric');
            if (ele.value !== "" && ele.value >=10 && ele.value<=100) {
                alert("Submitted");
            }
    }
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { NumericTextBoxModule } from '@syncfusion/ej2-angular-inputs';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,FormsModule, NumericTextBoxModule
    ],
    declarations: [AppComponent ],
    bootstrap: [AppComponent]
})
export class AppModule { }
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';

enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);
<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 Angular NumericTextBox</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Angular NumericTextBox Component" />
    <meta name="author" content="Syncfusion" />
    <!-- Here we have used CDN links for our preview purpose  -->
    <link href="index.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-angular-inputs/styles/material.css" rel="stylesheet" />

    <script src="https://unpkg.com/core-js/client/shim.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/core-js/2.4.1/core.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/zone.js/0.6.25/zone.min.js"></script>
    <script src="https://unpkg.com/reflect-metadata@0.1.3"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
</head>

<body>
    <div id='ang_container'>
        <div class='wrap'>
            <app-root>
                <div id='loader'>LOADING....</div>
               
            </app-root>
        </div>
    </div>
</body>
   <style>
  
    .e-numeric.e-control-wrapper {
        margin-bottom: 15px;
    }
    label.e-error {
        margin-top: -10px;
    }
    
    </style>

</html>
#container {
    visibility: hidden;
}

#loader {
  color: #008cff;
  height: 40px;
  left: 45%;
  position: absolute;
  top: 45%;
  width: 30%;
}

.wrap {
  margin: 35px auto;
  width: 240px;
  padding-top: 100px;
}