JSFiddle - React, Tailwind, and code Playground
by Praveen Kumar Purushothaman
HTML
<form action="">
<!-- If you wanna make use of the new HTML5 Attributes, which you must do, you can do this: -->
<input type="tel" pattern='[\+]\d{2}[\(]\d{2}[\)]\d{4}[\-]\d{4}' title="Phone Number (Format: +99(99)9999-9999)" placeholder="Phone Number (Format: +99(99)9999-9999)" />
<!-- The above format works only for the browsers, that support HTML5 Attributes! -->
<!-- If not, you can use the good ol' style! -->
<input type="text" class="mobile" />
<!-- And connect it to the JavaScript! -->
<!-- For validating the HTML5 -->
<input type="submit" />
</form>
CSS
* {font-family: 'Segoe UI'; padding: 5px;}
input {display: block; margin: 0 0 10px;}
JavaScript
$(document).ready(function () {
$(".mobile").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A, Command+A
(e.keyCode == 65 && ( e.ctrlKey === true || e.metaKey === true ) ) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
console.log(e.keyCode);
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
// Alert the user and do not allow!
if ((!e.shiftKey && !e.ctrlKey && !e.metaKey) || (e.ctrlKey && (e.keyCode == 86 || e.keyCode == 118)))
alert("Only numbers, no pasting contents!");
e.preventDefault();
}
}).blur(function () {
// Check the length if it is less than 10 digits.
if ($(this).val().length < 10 && $(this).val().length != 0)
// Alert the user!
alert("You have to have a mininum of 10 digits!");
});
});