简体   繁体   English

在显示给用户之前验证输入值

[英]Validate input value before it is shown to user

I have an html <input> and some pattern (eg -?\\d*\\.?\\d* float-signed value). 我有一个html <input>和一些模式(例如-?\\d*\\.?\\d*浮点值)。
I should prevent typing the not matched value. 我应该防止键入不匹配的值。
I did it in next way 我以另一种方式做到了

jQuery.fn.numeric = function (pattern) 
{
   var jqElement = $(this), prevValue;
    jqElement.keydown(function()
    {
                          prevValue = jqElement.val();
    })
    jqElement.keyup(function(e)
    {
       if (!pattern.test(jqElement.val()))
       {
          jqElement.val(prevValue);
          e.preventDefault();
       }
       prevValue = ""
    }) 
};  

JSFiddle DEMO JSFiddle演示

But in this case, value is shown to user and then corrected to right value. 但是在这种情况下,会向用户显示值,然后将其更正为正确的值。
Is it way to vaidate value before it is shown to user? 在显示给用户之前,是否有办法验证价值?

I can use pattern attribute from html5 我可以使用html5 pattern属性

$("#validateMe").on('keydown', function() {
    var charBeingTyped = String.fromCharCode(e.charCode || e.which); // get character being typed
    var cursorPosition = $(this)[0].selectionStart;        // get cursor position
    // insert char being typed in our copy of the value of the input at the position of the cursor.
    var inValue = $(this).value().substring(0, cursorPosition) + charBeingTyped + $(this).value().substring(cursorPosition, $(this).value().length);
    if(inValue.match(/-?\d*\.?\d*/)) return true;
    else return false;
});

How about this POJS, I'm using a cross-browser addEvent function instead of jquery and not using any regexs, but I believe it achieves what you are looking for. 如何使用此POJS,我使用的是跨浏览器的addEvent函数而不是jquery,并且未使用任何正则表达式,但是我相信它可以实现您所寻找的功能。 Pressing + or - changes the sign of the value. +-更改值的符号。

HTML HTML

<input id="test" type="text" />

Javascript 使用Javascript

/*jslint maxerr: 50, indent: 4, browser: true */


(function () {
    "use strict";

    function addEvent(elem, event, fn) {
        if (typeof elem === "string") {
            elem = document.getElementById(elem);
        }

        function listenHandler(e) {
            var ret = fn.apply(null, arguments);

            if (ret === false) {
                e.stopPropagation();
                e.preventDefault();
            }

            return ret;
        }

        function attachHandler() {
            window.event.target = window.event.srcElement;

            var ret = fn.call(elem, window.event);

            if (ret === false) {
                window.event.returnValue = false;
                window.event.cancelBubble = true;
            }

            return ret;
        }

        if (elem.addEventListener) {
            elem.addEventListener(event, listenHandler, false);
        } else {
            elem.attachEvent("on" + event, attachHandler);
        }
    }

    function verify(e) {
        var target = e.target, // shouldn't be needed: || e.srcElement;
            value = target.value,
            char = String.fromCharCode(e.keyCode || e.charCode);

        if (value.charAt(0) === "-") {
            if (char === "+") {
                e.target.value = value.slice(1);
            }
        } else if (char === "-") {
            e.target.value = char + value;
            return false;
        }

        value += char;
        return parseFloat(value) === +value;
    }

    addEvent("test", "keypress", verify);
}());

On jsfiddle jsfiddle上

I think I used the correct values keyCode || charCode 我想我使用了正确的值keyCode || charCode keyCode || charCode but you may want to search and check. keyCode || charCode但您可能要搜索和检查。 A summary of the correct ones are available here 正确的总结在这里

You could use this code to find out what character is pressed. 您可以使用此代码找出按下了哪个字符。 Validate that character and, if it validates, append it to the input field. 验证该字符,如果验证,则将其附加到输入字段。

Try this code: 试试这个代码:

 jQuery.fn.numeric = function (pattern) { $(this).keypress(function(e) { var sChar = String.fromCharCode(!e.charCode ? e.which : event.charCode); e.preventDefault(); var sPrev = $(this).val(); if(!pattern.test(sChar)){ return false; } else { sPrev = sPrev + sChar; } $(this).val(sPrev); }); }; $("#validateId").numeric(/^-?\\d*\\.?\\d*$/); 

jsfiddle.net/aBNtH/ jsfiddle.net/aBNtH/

UPDATE: My example validates each charachter while typing. 更新:我的示例在键入时验证了每个字符。 If you prefer to check the entire value of the input field instead, I would suggest to validate the value on an other Event, like Input blur(). 如果您宁愿检查输入字段的整个值,我建议在另一个Event上验证该值,例如Input blur()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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