[英]Validate input value before it is shown to user
我有一個html <input>
和一些模式(例如-?\\d*\\.?\\d*
浮點值)。
我應該防止鍵入不匹配的值。
我以另一種方式做到了
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 = ""
})
};
但是在這種情況下,會向用戶顯示值,然后將其更正為正確的值。
在顯示給用戶之前,是否有辦法驗證價值?
我可以使用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;
});
如何使用此POJS,我使用的是跨瀏覽器的addEvent
函數而不是jquery,並且未使用任何正則表達式,但是我相信它可以實現您所尋找的功能。 按+
或-
更改值的符號。
HTML
<input id="test" type="text" />
使用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);
}());
我想我使用了正確的值keyCode || charCode
keyCode || charCode
但您可能要搜索和檢查。 正確的總結在這里
您可以使用此代碼找出按下了哪個字符。 驗證該字符,如果驗證,則將其附加到輸入字段。
試試這個代碼:
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*$/);
更新:我的示例在鍵入時驗證了每個字符。 如果您寧願檢查輸入字段的整個值,我建議在另一個Event上驗證該值,例如Input blur()。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.