Regex to allow numbers only
Solution
In JQuery
var checkNumbers = function (textBox) {
debugger;
var regexp = new RegExp('^[0-9]+$');
var check = textBox.value;
if (!regexp.test(check)) {
alert('Invalid Value. Please enter numbers only');
$(textBox).css('border-color', 'red');
return false;
}
else {
$(textBox).css('border-color', 'green');
$(textBox).value = check;
return true;
}
}
In HTML
@Html.TextBox("AddAge", null, new { @class = "form-control text-box" @onchange = "checkNumbers(this)" })
Explanation
If you want your input to be restricted to allow numbers only, you can use this regex in the function. It will declare any other input that is non-numeric in nature as invalid and make the borders of text box red.
Leave a comment