JavaScript to only allow certain digits, and not submit if condition isn't met

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


JavaScript to only allow certain digits, and not submit if condition isn't met



I have a Contract ID form field:


<div class="form-group">
<label>Old Contract ID</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-hashtag"></i></span>
<input name="Contract.OldContractNumber" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type="number" class="form-control" maxlength="9" required>
</div>
</div>



I would like to add a piece of JavaScript that allows numbers only, that allows only 9 digits, and that only submits if 9 digits are there. Any less than 9 digits should not allow submission. Can someone help me achieve this?





What have you tried so far? What errors/issues have you run into?
– FrankerZ
yesterday







As you can see, I have oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type="number" maxlength="9" This allows 9 digits, but I'm not sure how to do it so that it does not submit if it is under 9 digits.
– Dana Lagnud
yesterday


oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type="number" maxlength="9"





Is there any reason you’re using an oninput attribute? Inline event handlers like onclick or oninput are not recommended. They are an obsolete, hard-to-maintain and unintuitive way of registering events. Always use addEventListener instead. Then you may use preventDefault.
– Xufox
yesterday




oninput


onclick


oninput


addEventListener


preventDefault





@Xufox no ultimate reason, just using it to test at the moment
– Dana Lagnud
yesterday





Hook into the onsubmit handler for the form, and test if the input value is less than 9 digits, and call event.preventDefault(); if it is. Plenty of tutorials online.
– FrankerZ
yesterday


onsubmit


event.preventDefault();




2 Answers
2




let input = document.getElementById('number')
let submitButton = document.getElementById('submit')
let pattern = /^d{9}$/


function checkValue () {
if (pattern.test(input.value)) {
submitButton.removeAttribute('disabled')
} else {
submitButton.setAttribute('disabled', 'disabled')
}
}


<form>
<input type="number" oninput="checkValue()" id="number">
<button type="submit" id="submit" disabled>Submit</button>
</form>



For preventing form submission for invalid input (less than 9 digits) use this:


document.getElementById("formID").addEventListener("submit", function(e){
var input = document.getElementsByName("Contract.OldContractNumber")[0].value;
if(input.length<9){
e.preventDefault();
}
});




<div class="form-group">
<form id="formID">
<label>Old Contract ID</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-hashtag"></i></span>
<input type="text" name="Contract.OldContractNumber" id="ContractOldContractNumber" maxlength="9" required>
<input type="submit" value="Submit"/>
</div>
</form>
</div>
<p/>
<span id="result"></span>
<script>
document.getElementById("formID").addEventListener("submit", function(e){
var input = document.getElementsByName("Contract.OldContractNumber")[0].value;
if(input.length<9){
e.preventDefault();
document.getElementById("result").innerHTML = "<b style='color: red;'>Input must be 9 digits!</b>";
} else {
document.getElementById("result").innerHTML = "";
}
});
</script>



You can use the following code to prevent non-numeric input (from frans' answer to this StackOverflow question.




<div class="form-group">
<label>Old Contract ID</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-hashtag"></i></span>
<input type="text" name="ContractOldContractNumber" id="ContractOldContractNumber" maxlength="9" required>
</div>
</div>
<script>
function InputValidator(input, validationType, validChars) {
if (input === null || input.nodeType !== 1 || input.type !== 'text' && input.type !== 'number')
throw ('Please specify a valid input');

if (!(InputValidator.ValidationType.hasOwnProperty(validationType) || validationType))
throw 'Please specify a valid Validation type';

input.InputValidator = this;

input.InputValidator.ValidCodes = ;

input.InputValidator.ValidCodes.Add = function (item) {
this[this.length] = item;
};

input.InputValidator.ValidCodes.hasValue = function (value, target) {
var i;
for (i = 0; i < this.length; i++) {
if (typeof (target) === 'undefined') {
if (this[i] === value)
return true;
}
else {
if (this[i][target] === value)
return true;
}
}

return false;
};

var commandKeys = {
'backspace': 8,
'tab': 9,
'enter': 13,
'shift': 16,
'ctrl': 17,
'alt': 18,
'pause/break': 19,
'caps lock': 20,
'escape': 27,
'page up': 33,
'page down': 34,
'end': 35,
'home': 36,
'left arrow': 37,
'up arrow': 38,
'right arrow': 39,
'down arrow': 40,
'insert': 45,
'delete': 46,
'left window key': 91,
'right window key': 92,
'select key': 93,
/*creates Confusion in IE */
//'f1': 112,
//'f2': 113,
//'f3': 114,
//'f4': 115,
//'f5': 116,
//'f6': 117,
//'f7': 118,
//'f8': 119,
//'f9': 120,
//'f10': 121,
//'f11': 122,
//'f12': 123,
'num lock': 144,
'scroll lock': 145,
};

commandKeys.hasValue = function (value) {
for (var a in this) {
if (this[a] === value)
return true;
}

return false;
};

function getCharCodes(arrTarget, chars) {
for (var i = 0; i < chars.length; i++) {
arrTarget.Add(chars[i].charCodeAt(0));
}
}

function triggerEvent(name, element) {
if (document.createEventObject) {
// dispatch for IE
var evt = document.createEventObject();
return element.fireEvent('on' + name, evt)
}
else {
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
evt.initEvent(name, true, true); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
}
}

if (validationType == InputValidator.ValidationType.Custom) {
if (typeof (validChars) === 'undefined')
throw 'Please add valid characters';

getCharCodes(input.InputValidator.ValidCodes, validChars);
}
else if (validationType == InputValidator.ValidationType.Decimal) {
getCharCodes(input.InputValidator.ValidCodes, '0123456789.');
}
else if (validationType == InputValidator.ValidationType.Numeric) {
getCharCodes(input.InputValidator.ValidCodes, '0123456789');
}

input.InputValidator.ValidateChar = function (c) {
return this.ValidCodes.hasValue(c.charCodeAt(0));
}

input.InputValidator.ValidateString = function (s) {
var arr = s.split('');

for (var i = 0; i < arr.length; i++) {
if (!this.ValidateChar(arr[i])) {
arr[i] = '';
}
}

return arr.join('');
}

function bindEvent(el, eventName, eventHandler) {
if (el.addEventListener) {
el.addEventListener(eventName, eventHandler, false);
} else if (el.attachEvent) {
el.attachEvent('on' + eventName, eventHandler);
}
}

function getCaretPosition(i) {
if (!i) return;

if ('selectionStart' in i) {
return i.selectionStart;
}
else {
if (document.selection) {
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart('character', -i.value.length);
return sel.text.length - selLen;
}
}
}

function setCursor(node, pos) {
var node = (typeof (node) === "string" || node instanceof String) ? document.getElementById(node) : node;

if (!node) {
return false;
}
else if (node.createTextRange) {
var textRange = node.createTextRange();
textRange.collapse(true);
textRange.moveEnd(pos);
textRange.moveStart(pos);
textRange.select();
return true;
} else if (node.setSelectionRange) {
node.setSelectionRange(pos, pos);
return true;
}

return false;
}

function validateActive() {
if (input.isActive) {
var pos = getCaretPosition(input);

var arr = input.value.split('');

for (var i = 0; i < arr.length; i++) {
if (!this.ValidateChar(arr[i])) {
arr[i] = '';

if (pos > i)
pos--;
}
}
console.log('before : ' + input.value);

input.value = arr.join('');
console.log('after : ' + input.value, input);
setCursor(input, pos);

setTimeout(validateActive, 10);
}
}

bindEvent(input, 'keypress', function (e) {
var evt = e || window.event;
var charCode = evt.which || evt.keyCode;

if (!input.InputValidator.ValidCodes.hasValue(charCode) && !commandKeys.hasValue(charCode)) {
if (evt.preventDefault) {
evt.preventDefault();
evt.stopPropagation();
}
return false;
}
});

bindEvent(input, 'keyup', function (e) {
var evt = e || window.event;
var charCode = evt.which || evt.keyCode;

if (!input.InputValidator.ValidCodes.hasValue(charCode) && !commandKeys.hasValue(charCode)) {
if (evt.preventDefault) {
evt.preventDefault();
evt.stopPropagation();
}
return false;
}
});

bindEvent(input, 'change', function (e) {
var dt = input.value;

input.value = input.InputValidator.ValidateString(input.value);

if (input.value !== dt)
triggerEvent('change', input);
});

bindEvent(input, 'blur', function (e) {
var dt = input.value;
input.value = input.InputValidator.ValidateString(input.value);

input.isActive = false;

if (input.value !== dt)
triggerEvent('blur', input);
});

bindEvent(input, 'paste', function (e) {
var evt = e || window.event;
var svt = input.value;

if (evt && evt.clipboardData && evt.clipboardData.getData) {// Webkit - get data from clipboard, put into editdiv, cleanup, then cancel event
if (/text/html/.test(evt.clipboardData.types)) {
var dt = evt.clipboardData.getData('text/html');

input.value = input.InputValidator.ValidateString(dt);
if (input.value !== dt)
triggerEvent('change', input);
}
else if (/text/plain/.test(e.clipboardData.types)) {
var dt = evt.clipboardData.getData('text/plain');

input.value = input.InputValidator.ValidateString(dt);
if (input.value !== dt)
triggerEvent('change', input);
}
else {
input.value = '';
}
waitforpastedata(input, svt);
if (e.preventDefault) {
e.stopPropagation();
e.preventDefault();
}
return false;
}
else {// Everything else - empty editdiv and allow browser to paste content into it, then cleanup
input.value = '';
waitforpastedata(input, svt);
return true;
}
});

bindEvent(input, 'select', function (e) {
var evt = e || window.event;

if (evt.preventDefault) {
evt.preventDefault();
evt.stopPropagation();
}
return false;
});

bindEvent(input, 'selectstart', function (e) {
var evt = e || window.event;

if (evt.preventDefault) {
evt.preventDefault();
evt.stopPropagation();
}
return false;
});

/* no need to validate wile active,
removing F keys fixed IE compatability*/
//bindEvent(input, 'fucus', function (e) {
// input.isActive = true;
// validateActive();
//});

//validate current value of the textbox
{
var dt = input.value;
input.value = input.InputValidator.ValidateString(input.value);

//trigger event to indicate value has changed
if (input.value !== dt)
triggerEvent('change', input);
}

function waitforpastedata(elem, savedcontent) {
if (elem.value !== '') {
var dt = input.value;
elem.value = elem.InputValidator.ValidateString(elem.value);

if (input.value !== dt)
triggerEvent('change', input);
}
else {
var that = {
e: elem,
s: savedcontent
}
that.callself = function () {
waitforpastedata(that.e, that.s)
}
setTimeout(that.callself, 10);
}
}
}

InputValidator.ValidationType = new (function (types) {
for (var i = 0; i < types.length; i++) {
this[types[i]] = types[i];
}
})(['Numeric', 'Custom', 'Decimal']);
new InputValidator(document.getElementById('ContractOldContractNumber'), InputValidator.ValidationType.Numeric);
</script>



Combined:




<div class="form-group">
<form id="formID">
<label>Old Contract ID</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-hashtag"></i></span>
<input type="text" name="Contract.OldContractNumber" id="ContractOldContractNumber" maxlength="9" required>
<input type="submit" value="Submit"/>
</div>
</form>
</div>
<p/>
<span id="result"></span>
<script>
document.getElementById("formID").addEventListener("submit", function(e){
var input = document.getElementsByName("Contract.OldContractNumber")[0].value;
if(input.length<9){
e.preventDefault();
document.getElementById("result").innerHTML = "<b style='color: red;'>Input must be 9 digits!</b>";
} else {
document.getElementById("result").innerHTML = "";
}
});
function InputValidator(input, validationType, validChars) {
if (input === null || input.nodeType !== 1 || input.type !== 'text' && input.type !== 'number')
throw ('Please specify a valid input');

if (!(InputValidator.ValidationType.hasOwnProperty(validationType) || validationType))
throw 'Please specify a valid Validation type';

input.InputValidator = this;

input.InputValidator.ValidCodes = ;

input.InputValidator.ValidCodes.Add = function (item) {
this[this.length] = item;
};

input.InputValidator.ValidCodes.hasValue = function (value, target) {
var i;
for (i = 0; i < this.length; i++) {
if (typeof (target) === 'undefined') {
if (this[i] === value)
return true;
}
else {
if (this[i][target] === value)
return true;
}
}

return false;
};

var commandKeys = {
'backspace': 8,
'tab': 9,
'enter': 13,
'shift': 16,
'ctrl': 17,
'alt': 18,
'pause/break': 19,
'caps lock': 20,
'escape': 27,
'page up': 33,
'page down': 34,
'end': 35,
'home': 36,
'left arrow': 37,
'up arrow': 38,
'right arrow': 39,
'down arrow': 40,
'insert': 45,
'delete': 46,
'left window key': 91,
'right window key': 92,
'select key': 93,
/*creates Confusion in IE */
//'f1': 112,
//'f2': 113,
//'f3': 114,
//'f4': 115,
//'f5': 116,
//'f6': 117,
//'f7': 118,
//'f8': 119,
//'f9': 120,
//'f10': 121,
//'f11': 122,
//'f12': 123,
'num lock': 144,
'scroll lock': 145,
};

commandKeys.hasValue = function (value) {
for (var a in this) {
if (this[a] === value)
return true;
}

return false;
};

function getCharCodes(arrTarget, chars) {
for (var i = 0; i < chars.length; i++) {
arrTarget.Add(chars[i].charCodeAt(0));
}
}

function triggerEvent(name, element) {
if (document.createEventObject) {
// dispatch for IE
var evt = document.createEventObject();
return element.fireEvent('on' + name, evt)
}
else {
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
evt.initEvent(name, true, true); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
}
}

if (validationType == InputValidator.ValidationType.Custom) {
if (typeof (validChars) === 'undefined')
throw 'Please add valid characters';

getCharCodes(input.InputValidator.ValidCodes, validChars);
}
else if (validationType == InputValidator.ValidationType.Decimal) {
getCharCodes(input.InputValidator.ValidCodes, '0123456789.');
}
else if (validationType == InputValidator.ValidationType.Numeric) {
getCharCodes(input.InputValidator.ValidCodes, '0123456789');
}

input.InputValidator.ValidateChar = function (c) {
return this.ValidCodes.hasValue(c.charCodeAt(0));
}

input.InputValidator.ValidateString = function (s) {
var arr = s.split('');

for (var i = 0; i < arr.length; i++) {
if (!this.ValidateChar(arr[i])) {
arr[i] = '';
}
}

return arr.join('');
}

function bindEvent(el, eventName, eventHandler) {
if (el.addEventListener) {
el.addEventListener(eventName, eventHandler, false);
} else if (el.attachEvent) {
el.attachEvent('on' + eventName, eventHandler);
}
}

function getCaretPosition(i) {
if (!i) return;

if ('selectionStart' in i) {
return i.selectionStart;
}
else {
if (document.selection) {
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart('character', -i.value.length);
return sel.text.length - selLen;
}
}
}

function setCursor(node, pos) {
var node = (typeof (node) === "string" || node instanceof String) ? document.getElementById(node) : node;

if (!node) {
return false;
}
else if (node.createTextRange) {
var textRange = node.createTextRange();
textRange.collapse(true);
textRange.moveEnd(pos);
textRange.moveStart(pos);
textRange.select();
return true;
} else if (node.setSelectionRange) {
node.setSelectionRange(pos, pos);
return true;
}

return false;
}

function validateActive() {
if (input.isActive) {
var pos = getCaretPosition(input);

var arr = input.value.split('');

for (var i = 0; i < arr.length; i++) {
if (!this.ValidateChar(arr[i])) {
arr[i] = '';

if (pos > i)
pos--;
}
}
console.log('before : ' + input.value);

input.value = arr.join('');
console.log('after : ' + input.value, input);
setCursor(input, pos);

setTimeout(validateActive, 10);
}
}

bindEvent(input, 'keypress', function (e) {
var evt = e || window.event;
var charCode = evt.which || evt.keyCode;

if (!input.InputValidator.ValidCodes.hasValue(charCode) && !commandKeys.hasValue(charCode)) {
if (evt.preventDefault) {
evt.preventDefault();
evt.stopPropagation();
}
return false;
}
});

bindEvent(input, 'keyup', function (e) {
var evt = e || window.event;
var charCode = evt.which || evt.keyCode;

if (!input.InputValidator.ValidCodes.hasValue(charCode) && !commandKeys.hasValue(charCode)) {
if (evt.preventDefault) {
evt.preventDefault();
evt.stopPropagation();
}
return false;
}
});

bindEvent(input, 'change', function (e) {
var dt = input.value;

input.value = input.InputValidator.ValidateString(input.value);

if (input.value !== dt)
triggerEvent('change', input);
});

bindEvent(input, 'blur', function (e) {
var dt = input.value;
input.value = input.InputValidator.ValidateString(input.value);

input.isActive = false;

if (input.value !== dt)
triggerEvent('blur', input);
});

bindEvent(input, 'paste', function (e) {
var evt = e || window.event;
var svt = input.value;

if (evt && evt.clipboardData && evt.clipboardData.getData) {// Webkit - get data from clipboard, put into editdiv, cleanup, then cancel event
if (/text/html/.test(evt.clipboardData.types)) {
var dt = evt.clipboardData.getData('text/html');

input.value = input.InputValidator.ValidateString(dt);
if (input.value !== dt)
triggerEvent('change', input);
}
else if (/text/plain/.test(e.clipboardData.types)) {
var dt = evt.clipboardData.getData('text/plain');

input.value = input.InputValidator.ValidateString(dt);
if (input.value !== dt)
triggerEvent('change', input);
}
else {
input.value = '';
}
waitforpastedata(input, svt);
if (e.preventDefault) {
e.stopPropagation();
e.preventDefault();
}
return false;
}
else {// Everything else - empty editdiv and allow browser to paste content into it, then cleanup
input.value = '';
waitforpastedata(input, svt);
return true;
}
});

bindEvent(input, 'select', function (e) {
var evt = e || window.event;

if (evt.preventDefault) {
evt.preventDefault();
evt.stopPropagation();
}
return false;
});

bindEvent(input, 'selectstart', function (e) {
var evt = e || window.event;

if (evt.preventDefault) {
evt.preventDefault();
evt.stopPropagation();
}
return false;
});

/* no need to validate wile active,
removing F keys fixed IE compatability*/
//bindEvent(input, 'fucus', function (e) {
// input.isActive = true;
// validateActive();
//});

//validate current value of the textbox
{
var dt = input.value;
input.value = input.InputValidator.ValidateString(input.value);

//trigger event to indicate value has changed
if (input.value !== dt)
triggerEvent('change', input);
}

function waitforpastedata(elem, savedcontent) {
if (elem.value !== '') {
var dt = input.value;
elem.value = elem.InputValidator.ValidateString(elem.value);

if (input.value !== dt)
triggerEvent('change', input);
}
else {
var that = {
e: elem,
s: savedcontent
}
that.callself = function () {
waitforpastedata(that.e, that.s)
}
setTimeout(that.callself, 10);
}
}
}

InputValidator.ValidationType = new (function (types) {
for (var i = 0; i < types.length; i++) {
this[types[i]] = types[i];
}
})(['Numeric', 'Custom', 'Decimal']);
new InputValidator(document.getElementById('ContractOldContractNumber'), InputValidator.ValidationType.Numeric);
</script>






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Keycloak server returning user_not_found error when user is already imported with LDAP

PHP parse/syntax errors; and how to solve them?

How to scale/resize CVPixelBufferRef in objective C, iOS