different input valdations for mobile and desktop based on regex
// source http://jsbin.com/fenoja
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="description" content="different input valdations for mobile and desktop based on regex">
<meta name="viewport" content="width=device-width">
<!-- <input type="text" id="inp" maxLength="5"> -->
<input type="text" id="inp" maxLength="5">
<script type="text/javascript">
var filterNonNumericCharacters = function (e)
{
console.log(e.which)
var isNumeric = (e.metaKey || // cmd/ctrl
e.which <= 0 || // arrow keys
e.which == 8 || // delete key
/[0-9]/.test(String.fromCharCode(e.which))); // numbers
if (!isNumeric)
{
e.preventDefault();
}
else
{
var element = e.target || null;
if (element)
{
lengthValidator(element, e);
}
}
}
var lengthValidator = function (inputElement, e)
{
if (inputElement)
{
var maxLength = +inputElement.maxLength;
maxLength = (maxLength < 0) ? null : maxLength; //because it return -1 when not defined
if (maxLength)
{
if (inputElement.value.trim().length >= maxLength)
{
e.preventDefault();
}
}
}
}
function numberMobile(e){
e.target.value = e.target.value.replace(/[^\d]/g,'');
return false;
}
var validateInput = function (elem,options)
{
// find inserted or removed characters
function findDelta(value, prevValue)
{
var delta = '';
for (var i = 0; i < value.length; i++) {
var str = value.substr(0, i) +
value.substr(i + value.length - prevValue.length);
if (str === prevValue) delta =
value.substr(i, value.length - prevValue.length);
}
return delta;
}
function isValidChar(c)
{
return new RegExp(options.regex).test(c);
}
function isValidString(str)
{
for (var i = 0; i < str.length; i++)
if (!isValidChar(str.substr(i, 1))) return false;
return true;
}
elem.addEventListener('input', function ()
{
var val = this.value,
lastVal = this.getAttribute('data-lastVal');
// get inserted chars
var inserted = findDelta(val, lastVal);
// get removed chars
var removed = findDelta(lastVal, val);
// determine if user pasted content
var pasted = inserted.length > 1 || (!inserted && !removed);
if (pasted)
{
if (!isValidString(val)) this.value = lastVal;
}
else if (!removed)
{
if (!isValidChar(inserted)) this.value = lastVal;
}
// store current value as last value
this.setAttribute('data-lastVal', this.value);
});
elem.addEventListener('focus', function ()
{
this.setAttribute('data-lastVal', this.value);
});
return this;
};
var elem= document.querySelector("#inp");
console.log(elem);
//elem.addEventListener("keyup",numberMobile,false);
validateInput(elem,{ regex: '[0-9]' })
</script>
</head>
<body>
</body>
</html>