Search results

Perform custom validation using FormValidator

To perform custom validation on the MaskedTextBox use the FormValidator along with custom validation rules.

In the following example, the MaskedTextBox is validated for invalid mobile number 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 { MaskedTextBoxComponent  } from '@syncfusion/ej2-angular-inputs';
import { FormValidator, FormValidatorModel } from '@syncfusion/ej2-inputs';

@Component({
    selector: 'app-root',
    // sets mask format to the MaskedTextBox
    template: `
    <form #formElement class="form-horizontal">
        <div class="form-group">
            <div class="col-sm-6">
                <br/><ejs-maskedtextbox id="masktextbox" #mask="" mask='000-000-0000' name="mask_value" placeholder= 'Mobile Number' floatLabelType= 'Always'></ejs-maskedtextbox>
            </div>
                <button type="button" id="submit_btn" (click)="btnClick()" style="margin-top: 10px">Submit</button>
        </div>
    </form>
    `
})

export class AppComponent {
    @ViewChild('formElement') element;
    @ViewChild('mask') mask: MaskedTextBoxComponent;
    public formObject: FormValidator;
    ngAfterViewInit() {
        let customFn: (args: { [key: string]: string }) => boolean = (args: { [key: string]: string }) => {
        let argsLength = args.element.ej2_instances[0].value.length;
        if(argsLength != 0) {
            return argsLength >= 10;
        }
        else {
            return true;
        }
        };

        let custom: (args: { [key: string]: string }) => boolean = (args: { [key: string]: string }) => {
        let argsLength = args.element.ej2_instances[0].value.length;
        if(argsLength == 0) {
            return 0;
        }
        else {
            return argsLength;
        }
        };

        // sets required property in the FormValidator rules collection
        let options: FormValidatorModel = {
            rules: {
                'mask_value': { numberValue: [customFn, 'Enter valid mobile number'] },

            }
        }
        this.formObject = new FormValidator(this.element.nativeElement, options);

        //FormValidator rule is added for empty MaskedTextBox
        this.formObject.addRules('mask_value', { maxLength: [custom, 'Enter mobile number'] });
        // places error label outside the MaskedTextBox using the customPlacement event of FormValidator
        let customPlace: (element: HTMLElement, error: HTMLElement) => void = (element: HTMLElement, error: HTMLElement) => {
            document.querySelector(".form-group").appendChild(error);
        };
        this.formObject.customPlacement = customPlace;
    }
    public btnClick(): void {
        // validates the MaskedTextBox
        this.formObject.validate("mask_value");
        // checks for incomplete value and alerts the formt submit
        if (this.mask.element.value !== "" && this.mask.element.value.indexOf(this.mask.promptChar) === -1) {
            alert("Submitted");
        }
    }
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { MaskedTextBoxModule } from '@syncfusion/ej2-angular-inputs';
import { FormsModule } from '@angular/forms';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule, MaskedTextBoxModule, FormsModule
    ],
    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 MaskedTextBox</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Angular MaskedTextBox Component" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <!-- Here we have used CDN links for our preview purpose  -->
    <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-mask.e-control-wrapper {
  margin-bottom: 20px;
}

label.e-error {
  margin-top: -42px;
}
</style>
</html>
#container {
    visibility: hidden;
}

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

.wrap {
  margin: 0 auto;
  width: 240px;
}

.label {
    font-family: 'Helvetica Neue', 'Helvetica', 'Arial', 'sans-serif';
    font-size: 14px;
}