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.

razor
howto.cs
@section ControlsSection{

<form id="form-element">
    @Html.EJS().MaskedTextBox("mask1").Mask("000-000-0000").Placeholder("Mobile Number").FloatLabelType(FloatLabelType.Always).Created("onCreate").Render()
    @Html.EJS().Button("submit_btn").Content("Button").Render()
</form>

<script>
    
    var customFn = function (args) {
        var argsLength = args.element.ej2_instances[0].value.length;
        if (argsLength != 0) {
            return argsLength >= 10; }
        else return true;
    };
    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': { numberValue: [customFn, 'Enter valid mobile number'] },
        },
    };
    // defines FormValidator to validate the MaskedTextBox
    var formObject = new ej.inputs.FormValidator('#form-element', options);
    formObject.addRules('mask', { 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");
            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");
            }
    });

    function onCreate() {
        document.getElementById(this.element.id).setAttribute("name", "mask");
    }
</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.

razor
cursorPosition.cs
@section ControlsSection{ 

@Html.EJS().MaskedTextBox("mask1").Mask("00000-00000").Value("93828-32132").Placeholder("Default cursor position").FloatLabelType(FloatLabelType.Always).Render()
@Html.EJS().MaskedTextBox("mask2").Mask("00000-00000").Value("83929-43427").Placeholder("Cursor positioned at start").FloatLabelType(FloatLabelType.Always).Focus("onfocus").Render()
@Html.EJS().MaskedTextBox("mask3").Mask("00000-00000").Value("83929-32131").Placeholder("Cursor positioned at end").FloatLabelType(FloatLabelType.Always).Focus("onfocus1").Render()
@Html.EJS().MaskedTextBox("mask4").Mask("+1 000-000-0000").Value("234-432-4324").Placeholder("Cursor at specified position").FloatLabelType(FloatLabelType.Always).Focus("onfocus2").Render()

}
<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.

razor
numericKeypad.cs
@section ControlsSection{

@Html.EJS().MaskedTextBox("mask1").Mask("000-000-0000").Created("onCreate").Render()

}
    <script>
    function onCreate() {
            var key = document.getElementById("mask1");
            key.type = "tel";
    }
    </script>
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.

razor
customCss.cs
@section ControlsSection{
@Html.EJS().MaskedTextBox("mask4").Mask("00000").Value("42648").cssClass("e-style").Placeholder("Enter user ID").FloatLabelType(FloatLabelType.Always).Created("oncreated").Focus("onfocus").Render()

}
<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.

razor
modelBinding-core.cs
modelBinding-mvc.cs
@using Syncfusion.EJ2.Inputs
@using Syncfusion.EJ2
@model EJ2MVCSampleBrowser.Controllers.MaskValue
@section ControlsSection{
    @using (Html.BeginForm())
    {
        @Html.ValidationSummary(true)
        <div class="col-lg-12 control-section">
            <div id="wrapper">
                @Html.EJS().MaskedTextBoxFor(model => model.value, (Syncfusion.EJ2.Inputs.MaskedTextBox)ViewData["Mask"]).Width("200px").Created("onCreate").Render()
                <div>
                    @Html.ValidationMessageFor(model => model.value)
                </div>
                <div id="submitbutton">
                    @Html.EJS().Button("btn").Content("Post").Render()
                </div>
            </div>
        </div>
    }
    <script>
        function onCreate() {
            document.getElementById(this.element.id).setAttribute("name", "value");
        }
        </script>
    <style>

        #wrapper {
            max-width: 246px;
            margin: 30px auto;
            padding-top: 50px;
        }

        #submitbutton {
            margin-top: 20px;
            margin-left: 65px;
        }

        #control-content #wrapper .field-validation-error {
            color: red;
        }
    </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