Search results

How To

Perform custom validation on MaskedTextBox 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
index.tsx
index.html
import * as React from "react";
import * as ReactDOM from "react-dom";
import { MaskedTextBoxComponent } from '@syncfusion/ej2-react-inputs';
//import the form validator related functions
import { FormValidator, FormValidatorModel } from '@syncfusion/ej2-inputs';

class App extends React.Component<{}, {}> {
    public componentDidMount(): void {
        // checks the length of mask value and returns corresponding boolean value
        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;
        }
        };

        //if mask value length is 0, 0 is returned else the length is returned
        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;
        }
        };

        let options: FormValidatorModel = {
            rules: {
                //must specify the name attribute value in rules section with required validation
                'mask_value': { numberValue: [customFn, 'Enter valid mobile number'] }
            },
            customPlacement: (inputElement: HTMLElement, errorElement: HTMLElement) => {
                //to place the error message in custom position
                //errorElement - error text which will be displayed.
                document.querySelector("#masktextbox").appendChild(errorElement);
            }
        };
        let formObject: FormValidator = new FormValidator('#form-element', options);

        //FormValidator rule is added for empty MaskedTextBox
        formObject.addRules('mask_value', { maxLength: [custom, 'Enter mobile number'] });
        document.getElementById('submit_btn').addEventListener('click', function() {
              formObject.validate('mask_value');
              let ele: HTMLInputElement =document.getElementById('mask').ej2_instances[0];
               // checks for incomplete value and alerts the formt submit
              if (ele.value !== "" && ele.value.indexOf(ele.promptChar) === -1) {
                alert("Submitted");
               }
        });
    }
    render() {
        return (
          <div>
            <br/><MaskedTextBoxComponent  id="mask" name="mask_value" placeholder="Mobile Number" mask= "000-000-0000" floatLabelType='Always' />
            <button id="submit_btn" style={{ marginTop: '10px' }}>Submit</button>
          </div>
        );
    }
};
ReactDOM.render(<App />, document.getElementById('masktextbox'));
<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 React MaskedTextBox</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="React MaskedTextBox Component" />
    <meta name="author" content="Syncfusion" />
    <link href="styles.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-inputs/styles/material.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
</head>

<body>
    <div class='wrap'>
        <form id="form-element" class="form-horizontal">
            <div class="form-group">
                <div id='masktextbox'>
                    <div id='loader'>Loading....</div>
                </div>
                <br>
            </div>
        </form>
    </div>
    <style>
    .e-mask.e-control-wrapper {
        margin-bottom: 20px;
    }
    label.e-error {
        margin-top: -42px;
    }
    </style>
</body>

</html>

Setting cursor position in MaskedTextBox

By default, on focusing the MaskedTextBox the entire mask gets selected. You can customize by using any one of the following methods:

  • Setting cursor position at the start of the MaskedTextBox.
  • Setting cursor position at the end of the MaskedTextBox.
  • Setting cursor at the specified position in the MaskedTextBox.

Following is an example that demonstrates the above cases to set cursor position in the MaskedTextBox using focus event.

Source
Preview
index.tsx
index.html
import * as React from "react";
import * as ReactDOM from "react-dom";
import { MaskedTextBoxComponent } from '@syncfusion/ej2-react-inputs';

class App extends React.Component<{}, {}> {
    private masktextbox: MaskedTextBoxComponent;
    public onfocus(args) {
        //sets cursor position at start of MaskedTextBox
        args.selectionEnd= args.selectionStart;
    }
    public onfocus1(args) {
        //sets cursor position at end of MaskedTextBox
        args.selectionStart=args.selectionEnd;
    }
    public onfocus2(args) {
        //sets cursor at specified position
        args.selectionStart = 3;
        args.selectionEnd = 3;
    }
    render() {
        return (
          <div>
            <br/><MaskedTextBoxComponent name="mask_value1" placeholder="Default cursor position" mask= "00000-00000" value="93828-32132" floatLabelType='Always'/>
            <MaskedTextBoxComponent name="mask_value2" placeholder="Cursor positioned at start" mask= "00000-00000" value="83929-43427" floatLabelType='Always' ref={(scope) => { this.masktextbox = scope; }} focus={this.onfocus.bind(this)}/>
            <MaskedTextBoxComponent name="mask_value3" placeholder="Cursor positioned at end" mask= "00000-00000" value="83929-32131" floatLabelType='Always' ref={(scope) => { this.masktextbox = scope; }} focus={this.onfocus1.bind(this)}/>
            <MaskedTextBoxComponent name="mask_value4" placeholder="Cursor at specified position" mask= "+1 000-000-0000" value="234-432-4324" floatLabelType='Always' ref={(scope) => { this.masktextbox = scope; }} focus={this.onfocus2.bind(this)}/>
          </div>
        );
    }
};
ReactDOM.render(<App />, document.getElementById('masktextbox'));
<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 React MaskedTextBox</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="React MaskedTextBox Component" />
    <meta name="author" content="Syncfusion" />
    <link href="styles.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-inputs/styles/material.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
</head>

<body>
    <div class='wrap'>
        <form id="form-element" class="form-horizontal">
            <div class="form-group">
                <div id='masktextbox'>
                    <div id='loader'>Loading....</div>
                </div>
                <br>
                <div id="error" />
            </div>
        </form>
    </div>
</body>

</html>

Display numeric keypad in MaskedTextBox for mobile devices

By default, on focusing the MaskedTextBox, alphanumeric keypad will be displayed on mobile devices. Sometimes only numeric keypad for number values is needed, and this can be achieved by setting “type” property to tel. Refer to the following example to enable numeric keypad in MaskedTextBox.

Source
Preview
index.tsx
index.html
import * as React from "react";
import * as ReactDOM from "react-dom";
import { MaskedTextBoxComponent } from '@syncfusion/ej2-react-inputs';

class App extends React.Component<{}, {}> {
    private masktextbox: MaskedTextBoxComponent;
    render() {
        return (
          <div>
            <br/><MaskedTextBoxComponent name="mask_value" mask='999-99999' value= "342-45432" type="tel"/>
          </div>
        );
    }
};
ReactDOM.render(<App />, document.getElementById('masktextbox'));
<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 React MaskedTextBox</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="React MaskedTextBox Component" />
    <meta name="author" content="Syncfusion" />
    <link href="styles.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-inputs/styles/material.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
</head>

<body>
    <div class='wrap'>
        <form id="form-element" class="form-horizontal">
            <div class="form-group">
                <div id='masktextbox'>
                    <div id='loader'>Loading....</div>
                </div>
                <br>
                <div id="error" />
            </div>
        </form>
    </div>
</body>

</html>

Change the appearance of MaskedTextBox

The appearance of the MaskedTextBox can be changed by adding custom cssClass to the component and enabling styles. Refer to the following example to change the appearance of the MaskedTextBox.

Source
Preview
index.tsx
index.html
import * as React from "react";
import * as ReactDOM from "react-dom";
import { MaskedTextBoxComponent } from '@syncfusion/ej2-react-inputs';

class App extends React.Component<{}, {}> {
    private masktextbox: MaskedTextBoxComponent;

    public onfocus(args) {
        //sets cursor position at start of MaskedTextBox
        args.selectionEnd= args.selectionStart;
    }
    render() {
        return (
          <div>
            <br/>
            <MaskedTextBoxComponent id="mask1" name="mask_value" placeholder="Enter user ID" floatLabelType='Always' mask= "00000" cssClass="e-style" value= "42648" created={this.oncreated} ref={(scope) => { this.masktextbox = scope; }} focus={this.onfocus.bind(this)}/>
          </div>
        );
    }
};
ReactDOM.render(<App />, document.getElementById('masktextbox'));
<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 React MaskedTextBox</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="React MaskedTextBox Component" />
    <meta name="author" content="Syncfusion" />
    <link href="styles.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-inputs/styles/material.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
</head>

<body>
    <div class='wrap'>
        <form id="form-element" class="form-horizontal">
            <div class="form-group">
                <div id='masktextbox'>
                    <div id='loader'>Loading....</div>
                </div>
                <br>
                <div id="error" />
            </div>
        </form>
    </div>
    <style>
    .e-mask.e-style .e-control.e-maskedtextbox {
        color: #00ffff ;
        letter-spacing: 10px ;
        font-size: xx-large ;
        border: 1px ;
        border-color: #ffffff ;
    }
    
    .e-control-wrapper.e-mask.e-float-input.e-style .e-float-line::before {
        background: #ffffff ;
    }
    
    .e-control-wrapper.e-mask.e-float-input.e-style .e-float-line::after {
        background: #ffffff ;
    }
    
    .e-control-wrapper.e-mask.e-float-input.e-style .e-float-text.e-label-top {
        color: #00ffff ;
        font-size: medium ;
    }
    </style>
</body>

</html>