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.

tagHelper
howto.cs
@section ControlsSection{ 
    // sets required property in the FormValidator rules collection
<form id="form-element">
    <ejs-maskedtextbox id="mask1" name="mask_value" mask="000-000-0000" placeholder="Mobile Number" floatLabelType="Always" ></ejs-maskedtextbox>
    <ejs-button id="submit_btn" content="Button"></ejs-button>
</form>

}

 <script>
    // checks the length of mask value and returns corresponding boolean value
    var customFn = function (args) {
        var 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
    var custom = function (args) {
        var argsLength = args.element.ej2_instances[0].value.length;
        if (argsLength == 0) {
            return 0;
        }
        else {
            return argsLength;
        }
    };

    // sets required property in the FormValidator rules collection
    var options = {
        rules: {
            'mask_value': { numberValue: [customFn, 'Enter valid mobile number'] },
        },
    };
    // defines FormValidator to validate the MaskedTextBox
    var formObject = new ej.inputs.FormValidator('#form-element', options);

    //FormValidator rule is added for empty MaskedTextBox
    formObject.addRules('mask_value', { maxLength: [custom, 'Enter mobile number'] });

    // places error label outside the MaskedTextBox using the customPlacement event of FormValidator

    formObject.customPlacement = function (element, errorElement) {
        document.querySelector("#mask1").appendChild(errorElement);
    };
    document.getElementById("submit_btn").addEventListener('click', function () {
            formObject.validate("mask_value");
            var ele = document.getElementById('mask1');
            // checks for incomplete value and alerts the formt submit
            if (ele.value !== "" && ele.value.indexOf(mask.ej2_instances[0].promptChar) === -1) {
                alert("Submitted");
            }
    });

</script>
public ActionResult howto()
{
    return View();
}

Output be like the below.

MaskedTextBox Sample

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.

tagHelper
cursorPosition.cs
@section ControlsSection{ 
    <ejs-maskedtextbox id="mask1" name="mask_value1" mask="00000-00000" value='93828-32132' placeholder="Default cursor position" floatLabelType="Always"></ejs-maskedtextbox>
    <ejs-maskedtextbox id="mask2" name="mask_value2" mask="00000-00000" value='83929-43427' placeholder="Cursor positioned at start" floatLabelType="Always" focus="onfocus.bind(this)"></ejs-maskedtextbox>
    <ejs-maskedtextbox id="mask3" name="mask_value3" mask="00000-00000" value='83929-32131' placeholder="Cursor positioned at end" floatLabelType="Always" focus="onfocus2.bind(this)"></ejs-maskedtextbox>
    <ejs-maskedtextbox id="mask4" name="mask_value4" mask="+1 000-000-0000" value='234-432-4324' placeholder="Cursor at specified position" floatLabelType="Always" focus="onfocus3.bind(this)"></ejs-maskedtextbox>

}

 <script>

    function onfocus(args) {
        //sets cursor position at start of MaskedTextBox
        args.selectionEnd= args.selectionStart;
    }

    function onfocus1(args) {
        //sets cursor position at end of MaskedTextBox
        args.selectionStart=args.selectionEnd;
    }

    function onfocus2(args) {
        //sets cursor at specified position
        args.selectionStart = 3;
        args.selectionEnd = 3;
    }

</script>
public ActionResult cursorPosition()
{
    return View();
}

Output be like the below.

MaskedTextBox Sample

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.

tagHelper
numericKeypad.cs
@section ControlsSection{ 
    <ejs-maskedtextbox id="mask1" name="mask_value" mask='00000' type="tel"></ejs-maskedtextbox>
}
public ActionResult numericKeypad()
{
    return View();
}

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.

tagHelper
customCss.cs
@section ControlsSection{ 
    <ejs-maskedtextbox id="mask1" name="mask_value1" mask="00000" value='42648' placeholder="Enter user ID" cssClass="e-style" floatLabelType="Always"  focus="onfocus.bind(this)"></ejs-maskedtextbox>

}

 <script>

    function onfocus(args) {
        //sets cursor position at start of MaskedTextBox
        args.selectionEnd= args.selectionStart;
    }

</script>

<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>
public ActionResult customCss()
{
    return View();
}

Output be like the below.

MaskedTextBox Sample

MVC For and Model Binding

This section demonstrates the Strongly typed extension support in MaskedTextBox. The view which bind with any model is called as strongly typed view. You can bind any class as model to view. You can access model properties on that view. You can use data associated with model to render controls.

In this sample, first click the submit button to post the selected value in the MaskedTextBox. When posting the null value, validation error message will be shown below the MaskedTextBox.

tagHelper
modelBinding-core.cs
modelBinding-mvc.cs
@using Syncfusion.EJ2
@*@model directive allows you to access the model values*@
@model EJ2CoreSampleBrowser.Controllers.MaskedTextbox.MaskValue
@section ControlsSection{
    <div class="col-lg-12 control-section">
        <div class="content-wrapper">
            <form method="post">
                <ejs-maskedtextbox id="mask" name="value"  ejs-for="@Model.value"></ejs-maskedtextbox>
                <div id="errorMessage">
                    <span asp-validation-for="value"></span>
                </div>
                <div id="submitbutton">
                    <ejs-button id="submitButton" content="Submit"></ejs-button>
                </div>
            </form>
        </div>
    </div>
}
<style>
    .content-wrapper {
        width: 30%;
        margin: 0 auto;
        min-width: 185px;
    }

    .control-label {
        padding: 10px 0px 5px 0px;
        font-size: 12px;
    }

    #errorMessage {
        color: red;
        text-align: center
    }

    #submitbutton {
        margin: 10px auto;
        text-align: center;
    }
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;

namespace EJ2CoreSampleBrowser.Controllers.MaskedTextbox
{
    public class MaskValue
    {
        [Required]
        public string value { get; set; }

    }
    public partial class MaskedTextboxController : Controller
    {

        public IActionResult DefaultFunctionalities()
        {
            MaskValue val = new MaskValue();
            val.value = "10";
            return View(val);
        }
        [HttpPost]
        public IActionResult DefaultFunctionalities(MaskValue model)
        {
            MaskValue val = new MaskValue();
            val.value = model.value;
            return View(val);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;


namespace EJ2MVCSampleBrowser.Controllers
{
    public class MaskValue
    {
        [Required(ErrorMessage = "MaskedValue is required")]
        public string value { get; set; }
    }
    public partial class MaskedTextBoxController : Controller
    {
        public ActionResult DefaultFunctionalities()
        {
            MaskValue newmask = new MaskValue();
            Syncfusion.EJ2.Inputs.MaskedTextBox mask1 = new Syncfusion.EJ2.Inputs.MaskedTextBox();
            ViewData["Mask"] = mask1;
            return View(newmask);
        }
        [HttpPost]
        public ActionResult DefaultFunctionalities(MaskValue model)
        {

            MaskValue newmask = new MaskValue();
            Syncfusion.EJ2.Inputs.MaskedTextBox mask1 = new Syncfusion.EJ2.Inputs.MaskedTextBox();
            mask1.ShowClearButton = true;
            ViewData["Mask"] = mask1;
            return View(model);
        }
    }

}

Output be like the below.

MaskedTextBox Sample