Showing posts with label number-validation. Show all posts
Showing posts with label number-validation. Show all posts

Thursday, November 9, 2017

jQuery Number Text Field Validation Using Regex On Input Field

jQuery Number Text Field Validation Using Regex

Below is the full example of how to validate number using regex


var pattern = new RegExp("(^(\-?)([0-9]{0,12}?)(\\.)([0-9]){0,12}$)|(^(\-?)([0-9]){0,12}$)");

$(document.body).on("keypress", "input[type='text'].number", function (e) {
    if (e.which == 0 || e.which == 8) return true;
    var v = getTextFieldValue(this, String.fromCharCode(e.which));
    $("div").html(v);
    return pattern.test(v);
});

document.addEventListener("paste", function (e) {
    var v, f = $(e.target), ov = f.val();
    if (window.clipboardData && window.clipboardData.getData) { // IE
        v = window.clipboardData.getData('Text');
    }
    else if (e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.getData) {
        v = e.originalEvent.clipboardData.getData('text/plain');
    }
    else if (e.clipboardData && e.clipboardData.getData) {
        v = e.clipboardData.getData('text/plain');
    }
    v = getTextFieldValue(f[0], v);
    if (!pattern.test(v)) e.preventDefault();
    $("div").html(v);
});

function getTextFieldValue(input, nv) {
    var v = input.value, i = input.selectionStart, j = input.selectionEnd;

    if (i == 0 && j == v.length) return nv;
    else if (i != j || i > 0) return v.substr(0, i) + nv + v.substr(j);
    else if (i == 0) return nv + v;
    else return v + nv;
}

$("input[type='text'].number").focus();


And finally you can use below regex to test your number:
^[-+]?(?:\.[0-9]{1,12}|[0-9]{1,12}(?:\.[0-9]{0,12})?)(?:[eE][-+]?[0-9]{1,12})?$

You can experience above example in JsFiddle

You can also check in regex test environment