Change the color of the TextBox based on its value

17 Feb 20224 minutes to read

You can change the color of the TextBox by validating its value using regular expression in the keyup event for predicting the numeric values as demonstrated in the following code sample.

<div class='wrap'>
        <label>Normal Input</label>
        <div class="e-input-group">
            <input class="e-input" type="text" placeholder="Enter numeric values" onkeyup="onKeyup(this)" />
        </div>
        <label> Floating Input </label>
        <div class="e-float-input">
            <input type="text" onkeyup="onKeyup(this)" required />
            <span class="e-float-line"> </span>
            <label class="e-float-text">Enter numeric values</label>
        </div>
</div>

<script>
    ej.base.enableRipple(true);

    // To get the all input fields and its container.

    var inputElement = document.querySelectorAll('.e-input-group .e-input,.e-float-input.e-input-group input');

    // Add 'e-input-focus' class to the input for achive ripple effect when focus on the input field.

    for (var i = 0; i < inputElement.length; i++) {
        inputElement[i].addEventListener('focus', function () {
            var parentElement = this.parentNode;
            if (parentElement.classList.contains('e-input-in-wrap')) {
                parentElement.parentNode.classList.add('e-input-focus');
            } else {
                this.parentNode.classList.add('e-input-focus');
            }
        });
        inputElement[i].addEventListener('blur', function () {
            var parentElement = this.parentNode;
            if (parentElement.classList.contains('e-input-in-wrap')) {
                parentElement.parentNode.classList.remove('e-input-focus');
            } else {
                this.parentNode.classList.remove('e-input-focus');
            }
        });
    }
    function onKeyup(e) {
        let str = e.value.match(/^[0-9]+$/);
        if (!((str && str.length > 0)) && e.value.length) {
            e.parentElement.classList.add('e-error');
        } else {
            e.parentElement.classList.remove('e-error');
        }
    }
</script>

<style>
    .e-input-group.e-error .e-input { /* csslint allow: adjoining-classes */
        color: #f44336;
    }

    .e-float-input.e-error input { /* csslint allow: adjoining-classes */
        color: #f44336;
    }

    .wrap label { /* csslint allow: adjoining-classes */
        font-weight: bold;
    }
</style>
public ActionResult Index()
{
    return View();
}

Output be like the below.

textbox