this maybe a simple question but not for me. I have a form that has a phone number field in i have JS to restrict users to a certain format. The problem is when they input less then 10 digits it still allows them to submit.
Here is my js:
$('#phone-number')
.keydown(function (e) {
var key = e.which || e.charCode || e.keyCode || 0;
$phone = $(this);
// Don't let them remove the starting '('
if ($phone.val().length === 1 && (key === 8 || key === 46)) {
$phone.val('(');
return false;
}
// Reset if they highlight and type over first char.
else if ($phone.val().charAt(0) !== '(') {
$phone.val('(' + String.fromCharCode(e.keyCode) + '');
}
// Auto-format- do not expose the mask as the user begins to type
if (key !== 8 && key !== 9) {
if ($phone.val().length === 4) {
$phone.val($phone.val() + ')');
}
if ($phone.val().length === 5) {
$phone.val($phone.val() + ' ');
}
if ($phone.val().length === 9) {
$phone.val($phone.val() + '-');
}
}
// Allow numeric (and tab, backspace, delete) keys only
return (key == 8 ||
key == 9 ||
key == 46 ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
.bind('focus click', function () {
$phone = $(this);
if ($phone.val().length === 0) {
$phone.val('(');
}
else {
var val = $phone.val();
$phone.val('').val(val); // Ensure cursor remains at the end
}
})
.blur(function () {
$phone = $(this);
if ($phone.val() === '(') {
$phone.val('');
}
});
This is the phone number box:
<div class="form-group">
#Html.LabelFor(m => m.phoneNumber)
#Html.TextBoxFor(m => m.phoneNumber, new { #class = "form-control", minlength = "5", oncopy = "return false", onpaste = "return false",
id = "phone-number" ,name = "phone-number", type = "text", maxlength = "14" , placeholder = "(XXX) XXX-XXXX"
})
</div>
This is the Submit btn
<button type="submit" class="btn btn-primary" value="Results" id="Submit" disabled="disabled" >Submit</button>
I don't know if you need this information but this Enable the submit btn after the boxes are filled in JS
$("input[type=text]").keyup(function () {
if
(
$("#firstName").val().trim().length !== 0 &&
$("#lastName").val().trim().length !== 0 &&
// $("#phoneNumber").val().trim().length !== 0 &&
$("#address").val().trim().length !== 0
) {
$("#Submit").removeAttr("disabled");
$("#Submit").addClass("btn--primary");
} else {
$("#Submit").attr("disabled", "disabled");
}
});
Thank you and sorry if it is an easy question but I tried in many places.
What you want to do is stop the form submission from going through. You can do this by attaching an on submit event to the form and preventDefault within it. For example:
$('#FORM_ID').submit(function (e) {
if ($('#phone-number').val().replace(/[^\d]/g,'').length < 10){ // check if phone number is less than 10 digits
// phone number is less than 10 digits, prevent form submission
e.preventDefault()
return false
}
})
Let me know if you have any questions!
Here's how my validation of the phone number input ($('#phone-number').val().replace(/[^\d]/g,'').length < 10) works:
I get the value of the phone number input: $('#phone-number').val()
I remove any characters that are not numbers replace(/[^\d]/g,'')
Then I get the length of the resulting numbers. If it's less than 10, I prevent the form from submitting via e.preventDefault()
Note: you will have to replace #FORM_ID with the id of the form you want to run this validation for.
Have you considered using an input with type="tel" and the pattern attribute? It doesn't disable the submit button like you asked, but it can validate the user input against a certain pattern.
Below a few examples of inputs using a pattern. The first accepts exactly 10 digits, the second accepts 10 digits or more, the third accepts a strict format similar to your inputs placeholder:
<form>
<input type="tel" pattern="[0-9]{10}" placeholder="Exactly 10 digits"><br>
<input type="tel" pattern="[0-9]{10,}" placeholder="10 digits or more"><br>
<input type="tel" pattern="\([0-9]{3}\) [0-9]{3}-[0-9]{4}" maxlength="14" placeholder="(123) 456-7890"><br>
<input type="submit">
</form>
thank you for the help but for me this works the best and easiest.
//This script will prevent the user from Submitting if the Phone number box is less than
function validatePhone() {
var phoneNumberPattern = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
var phoneNumber = $("#phone-number").val();
if (phoneNumberPattern.test(phoneNumber)) {
return true;
}
return false;
}
//Here we make sure that all boxes are filled then Submit.
$("input[type=text]").keyup(function () {
if
(
validatePhone()
) {
$("#Submit").removeAttr("disabled");
$("#Submit").addClass("btn--primary");
} else {
$("#Submit").attr("disabled", "disabled");
}
});
//this is the submit btn
<div class="form-group">
<button type="submit" class="btn btn-primary" value="Results" id="Submit" disabled="disabled">Submit</button>
</div>
Related
Credit card expiration date: mm/yy
Whenever I enter two numbers, I need add /, but currently when I delete the third number, he will only delete one number. How can I delete the third number along with the slash?
Please help thank you.
var characterCount
$('#expiry').on('input', function(e) {
if ($(this).val().length == 2 && characterCount < $(this).val().length) {
$(this).val($(this).val() + '/');
}
characterCount = $(this).val().length
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="expiry" type="text" />
with plain js
const inp = document.querySelector('#expiry')
inp.onkeydown = function() {
const key = event.keyCode || event.charCode;
if (key !== 8 && key !== 46 ) {
if (inp.value.length == 2) {
inp.value= (inp.value+'/');
}
}
if (( key == 8 || key == 46 ) && inp.value.length === 4) {
inp.value = inp.value.slice(0,3)
}
};
<input id="expiry" type="text" />
You can add an additional keyup event and when the backspace key is hit, remove any trailing slash from the end of the value.
I'd also recommend to set the maxlength, pattern and inputmode attributes on the input.
var characterCount;
$('#expiry').on('input', function(e) {
if ($(this).val().length == 2 && characterCount < $(this).val().length) {
$(this).val($(this).val() + '/');
}
characterCount = $(this).val().length
}).on('keyup', function(e) {
if (e.which === 8) {
$(this).val($(this).val().replace(/\/$/, ''))
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="expiry" type="text" maxlength="5" pattern="^\d{2}/\d{2}$" inputmode="numeric" />
I want to check if a user inputs an invalid character when chosing his name. My code almost works. The only problem is when I type in a valid user name f.e. "John" and add an invalid character to it "John!!" it doesn't detect it. When I type in an invalid character only "!!!!" it gets detected.
HTML:
<input class="user-input" pattern="[a-zA-Z0-9._-ßÄÖÜäöü]{1,30}" type="text" id="idUsername" oninput='checkValidUsername();'" required disabled>
JavaScript:
function checkValidUsername()
{
var input = document.getElementById("idUsername").value;
if(input.search(/^[a-zA-Z0-9ßÄÖÜäöü_.-]/) == -1)
{
document.getElementById("idValidChars").style.visibility = "visible";
}
else
{
document.getElementById("idValidChars").style.visibility = "hidden";
}
}
You will have to change your regular expression to
/^[a-zA-Z0-9ßÄÖÜäöü_.-]+$/
This is because you need to check the whole string for a validity, instead of the first character as you did.
The + allows the previous sequence to appear more than one occurrence, and the $ restricts it to be the end of the string. Which means, that the string must start and end with only the characters you have indicated.
Try this:
$('#ID').keydown(function (e) {
if (e.shiftKey || e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
e.preventDefault();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="ID" type="text" />
(XXX) XXX-XXXX xXXXX
I want insert a X symbol after every 15th character in input. I have a Business Phone input box. When a user is typing and reaches each 15th character, then jQuery will insert a hyphen (X).
For example: (999) 999-9999 x9999
I'm trying some codes and i think i'm so close to correct code but i have some problems. Here is my code sample;
$(document).delegate('#businessPhone', 'keyup', function(e) {
var Textlength = $(this).val();
console.log(Textlength.length);
if (Textlength.length >= 14) {
//alert("if"+Textlength.length);
$("#businessPhone").mask("(999) 999-9999 x9999");
return false;
} else {
//alert("else"+Textlength.length);
$("#businessPhone").mask("(999) 999-9999");
}
});
Code is working fine as aspected if user complete enter all characters.
But problem is user wants to remove characters the characters did not delete if character length reach 14 .
try this
$('#phone-number', '#example-form')
.keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
$phone = $(this);
// Auto-format- do not expose the mask as the user begins to type
if (key !== 8 && key !== 9) {
if ($phone.val().length === 4) {
$phone.val($phone.val() + ')');
}
if ($phone.val().length === 5) {
$phone.val($phone.val() + ' ');
}
if ($phone.val().length === 9) {
$phone.val($phone.val() + '-');
}
if ($phone.val().length === 15) {
$phone.val($phone.val() + ' x');
}
}
// Allow numeric (and tab, backspace, delete) keys only
return (key == 8 ||
key == 9 ||
key == 46 ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
.bind('focus click', function () {
$phone = $(this);
if ($phone.val().length === 0) {
$phone.val('(');
}
else {
var val = $phone.val();
$phone.val('').val(val); // Ensure cursor remains at the end
}
})
.blur(function () {
$phone = $(this);
if ($phone.val() === '(') {
$phone.val('');
}
});
<form id="example-form" name="my-form">
<label>Phone number:</label><br />
<!-- I used an input type of text here so browsers like Chrome do not display the spin box -->
<input id="phone-number" name="phone-number" type="text" placeholder="(XXX) XXX-XXXX" /><br /><br />
<input type="button" value="Submit" />
</form>
How to set a range between 0 and 99 on a input type number? I am using HTML5 attributes ( min="0" max="99" ) but it's not working and as far as I know this kind of attribute is not supported by some browsers.
So I am using this script which blocks non-numerical characters but I want to limit the numbers to a max of 99 (only 2 digits). How can I do that?
Also I want to allow users to use the keyboard to type the numbers.
$(".js-number").numeric();
jsFiddle
<input class="test-input" type="number" maxlength="12" />
<script>
$('.test-input').unbind('keyup change input paste').bind('keyup change input paste',function(e){
var $this = $(this);
var val = $this.val();
var valLength = val.length;
var maxCount = $this.attr('maxlength');
if(valLength>maxCount){
$this.val($this.val().substring(0,maxCount));
}
});
</script>
Your example works if you remove the $(".js-number").numeric();
But you can edit the input.
maxlength attribute works on input type text, so I guess javascript validation is inevitable.
<input type="number" class="js-number" min="0" max="99" value="0">
<script>
$(".js-number").bind('keydown', function(e){
var targetValue = $(this).val();
if (e.which ===8 || e.which === 13 || e.which === 37 || e.which === 39 || e.which === 46) { return; }
if (e.which > 47 && e.which < 58 && targetValue.length < 2) {
var c = String.fromCharCode(e.which);
var val = parseInt(c);
var textVal = parseInt(targetValue || "0");
var result = textVal + val;
if (result < 0 || result > 99) {
e.preventDefault();
}
if (targetValue === "0") {
$(this).val(val);
e.preventDefault();
}
}
else {
e.preventDefault();
}
});
</script>
function format(input){
if(input.value < 0) input.value=Math.abs(input.value);
if(input.value.length > 2) input.value = input.value.slice(0, 2);
$(input).blur(function() {
// if(input.value.length == 1) input.value=0+input.value;
// if(input.value.length == 0) input.value='01';
//* if you want to allow insert only 2 digits *//
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" name="number" step="1" oninput="format(this)">
It works for me... hope for you as well :)
you can set like this:
<input type="text" class="js-number" maxlength="2">
You can just use maxlength="2" in input of html and this.value = this.value.replace(/[^\d]/, '') in Javascript function
maxlength="2" : It allows only two entries in the input by text (lets take it number) so the maximum two digit number is 99 and minimum two digit number is -9 (- is also considered as a entry) but if - sign is removed than minimum number is 00 , which solves the range of 00-99
Now the input is type=text so any alphabet can be entered along with symbols (- # $...) to solve that JavaScript Regular Expression
this.value = this.value.replace(/[^\d]/, '') : It take the value from the input on each entry of a digit and check if it is a number or not . If it is a number then the entry will be leaved as it is but if entry is not a number than it is replace by '' means removed from the input . So only number entry is solved without a - sign too
document.getElementsByClassName("orderUnits")[0].addEventListener("input", amountofUnits);
function amountofUnits() {
this.value = this.value.replace(/[^\d]/, '')
}
<input type="text" class="orderUnits" maxlength="2">
I wanted a text field to take only numbers ans some control keys and number should be exactly four digit long, not less not more. My validation code is
function checkValidInput()
{
$(".validateYearTextBox").keydown(function(event)
{
// Allow only delete, backspace,left arrow,right arraow and Tab
if (
event.keyCode == 46 //delete
|| event.keyCode == 8 //backspace
|| event.keyCode == 37 //leftarow
|| event.keyCode == 39 //rightarrow
|| event.keyCode == 9 //tab
)
{
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode <96 ||event.keyCode > 105) ) {
event.preventDefault();
}
}
});
$(".validateYearTextBox").keyup(function(event)
{
var val = $(this).val();
if (val.length > 4){
alert ("Max length is 4");
val = val.substring(0, valore.length - 1);
$(this).val(val);
$(this).focus();
return false;
}
});
}
Here, my first validation is working, but my send one is not working.
I am calling this validation function in my aspx page like this
<script type="text/javascript">
$(document).ready(function(){
checkValidInput();
}
</script>
What is going wrong?
Simplify it:
function checkValidInput() {
// Allow only delete, backspace, left arrow, right arrow,
// Tab, ctrl+v and numbers
$(".validateYearTextBox").keydown(function(event) {
if (!((event.keyCode == 46 ||
event.keyCode == 8 ||
event.keyCode == 37 ||
event.keyCode == 39 ||
event.keyCode == 9) ||
(event.ctrlKey && event.keyCode == 86) || // Edit: Added to allow ctrl+v
$(this).val().length < 4 &&
((event.keyCode >= 48 && event.keyCode <= 57) ||
(event.keyCode >= 96 && event.keyCode <= 105)))) {
// Stop the event
event.preventDefault();
return false;
}
});
// Edit: Added validate after copy+paste.
// This removes non-numeric characters and truncates the length
// to 4 if the user copy + pasted.
$(".validateYearTextBox").change(function(event) {
var value = $(this).val();
value = value.replace(/[^0-9]/g,'');
value = value.substr(0,4);
$(this).val(value);
});
}
$(document).ready(function() {
checkValidInput();
});
http://jsfiddle.net/nwellcome/687kD/
Edit: Personally I like the Masked Input jQuery plugin but that might be a heavy-handed solution if this is all you need to do.
There are many, many jQuery plugins that already do this in one form or another.
One that does mostly1 what you want is Masked Input Plugin. If you can, I recommend using something existing, working and proven, rather than reinventing.
1 The only part that it doesn't seem to do is display an error if a user tries to enter more than n characters but I'm sure you could modify the plugin or add a length check to the <input>
Use regular expression :
enter code here
function validator(elem,msg)
{
var exp=/^([0-9]+)$/; //it only allows for numbers
if(elem.value.match(exp))
{return true;}
else
{
alert(msg);
elem.focus();
return false;
}
}
the html code :
enter code here
<html><head>
<script src="javasript.js" type="text/javascript">
</head>
<body>
<form method=POST>
<input type='text' maxlength=4 name='num' id='num'>
<input type='submit' value=OK onClick="validator(document.getElementById('num'),'Only four numbers and numbers only!');">
</form> //the maxlength in input text tag restrict the maximum length of the input
</body></html>
Here's a simple way of doing it. Stores the old text before an event changes the text. Then check to see if the new text is valid or not. If it isn't, then revert back to the old text. To further ensure the maximum of 4 characters, add a maxlength attribute to all <input type="text"> elements.
jQuery.fn.forceNumericOnly = function() {
return this.each(function() {
var oldText;
$(this).keyup(function(e) {
var newText = $(this).val();
if (newText != "" && (isNaN(newText) || val.length > 4))
$(this).val(oldText);
else
oldText = $(this).val();
})
$(this).blur(function(e) {
var newText = $(this).val();
if (newText != "" && (isNaN(newText) || val.length > 4))
$(this).val(newText = oldText);
else
oldText = $(this).val();
});
})
};
$(".validateYearTextBox").forceNumericOnly();
if (document.ExamEntry.examnum.value=="") {
msg+="You must enter your examination number \n";
document.ExamEntry.examnum.focus();
document.getElementById('examnum').style.color="red";
result = false;
}
$('.numeric').keypress(function(e) {
var verified = (e.which == 8 || e.which == undefined || e.which == 0) ? null : String.fromCharCode(e.which).match(/[^0-9]/);
if (verified || e.delegateTarget.value.length>3 || e.ctrlKey ==true) { if(e.which!=8 ){e.preventDefault();}}
}).on('paste',function(e){ e.preventDefault();});
Here add class=numeric to input text box'. it will allow only 4 digits if you want to limit size to 2 digits change to e.delegateTarget.value.length>1 and so on as index starts from zero
Use HTML input maxlength attribute for this and also set the size value of fixing width 4 in same input size attribute.
<input type="text" maxlength="4" size="4">
Here is a simple answer that takes care of copy paste and all.
$(document).on("input", ".validateYearTextBox", function() {
var value = this.value
value = value.replace(/\D/g,'');
for (i = 0; i < value.length; i++) {
if (i > 3) {
value = value.replace(value[i], '')
}
}
});