简体   繁体   中英

Regular Expression to restrict from entering into textbox

Everybody

I am working on a sample MVC4 project and here I am trying to make sure that user can not type anything if the entered text is not equal to a decimal value(precision 7, and scale 2) by comparing the value with regex.

But I am unable to restrict the user from entering even when the regex test fails.

Please find the code below and let me know.

@Html.TextBoxFor(m => m.inFormModel[count].Unit, new { @type = "number", 
@step = "0.01", @max = "6", @onkeyup = "return isNumberKey(event, this);"}) 

And below is my javascript code

<script type="text/javascript">
function isNumberKey(evt, text) {
    var re = /^(\d{0,5}\.\d{0,2}|\d{0,5}|\.\d{0,2})$/;
    var typedValue = parseFloat(text.value);
    typedValue = typedValue.toFixed(2);
    if (re.test(typedValue) == false)
    {
        alert("does not match");
        return false;
    }
    else
    {
        alert("does match");
        return true;
    }
</script>

And I know we can validate from MVC models annotations, but I want to restrict user from entering.

Thanks in Advance.

It's not very clear what you are trying to accomplish but I am going to take an educated guess and say you want the textbox to accept numeric values only. By virtue of setting the type to number, you are restricting keyboard input of illegal characters but you are probably worried about people pasting bad stuff.

Either way, you want to use the keydown event instead Also, please note the code you pasted is missing a closing bracket.

Here is a possible solution. It's something I whipped out quickly so I am sure it can be improved, but you will get the general idea:

function isNumberKey(evt, text) 
{       
    if(!isAllowedKey(evt.keyCode)) 
    {
        var existingText = (text.value == null || text.value == "") ? "" : text.value;
        var tentativeValue = existingText + evt.key;
        var result = isNumeric(tentativeValue);         
        return result;
    }    
}

function isNumeric(n) 
{
    return !isNaN(parseFloat(n)) && isFinite(n);
}

function isAllowedKey(keyCode)
{
    var allowedKeys = [13,9,37,39, 46, 8, 16]; //Enter, tab, left, right, period, backspace, shift
    for(i = 0; i < allowedKeys.length; i++)
    {
        if(keyCode == allowedKeys[i])
            return true;
    }
    return false;
}

Here is a working fiddle:

https://jsfiddle.net/970oajaj/35/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM