Phone number validation using onblur seems to get in a loop - javascript

I am using the onblur attribute to call a Javascript phone number validation function. However, if the format of the number is invalid, after displaying an error message using alert(), when I click on the OK button the message is repeated immediately instead of focus being returned to the phone number field to allow me to correct the format. It's impossible to get out of the loop.
This is the code for it:
function validPhone(phoneNum)
// check for valid phone numbers in the format 999-999-9999
{
var strPhone = phoneNum.value;
var rePhone = /\d{3}-\d{3}-\d{4}/;
var blnResult = true;
if (strPhone.length !== 0 && (strPhone.length !== 12 || strPhone.match(rePhone) == null)) {
blnResult = false;
phoneNum.select();
alert("Phone number is invalid. Please try again.");
phoneNum.focus();
}
return blnResult;
}
<input type="text" name="homephone" size="12" onBlur="validPhone(this)"></input>
Does anyone know what is wrong with this? It is not working in Chrome or the Apple browser, but for some reason it works in IE 11.

Remove phoneNum.select() and phoneNum.focus().
Thoose instructions make fired a onBlur events, and you are in a loop with no end ...
You should turn your size attribute into maxLength.

Related

How do I detect whether or not an input with type=time has any values entered

I have a javascript script that's supposed to detect whenever an html form input with type="time" has any value entered.
However, whenever I enter a partial value (for instance, type one number, instead of a full time with AM/PM), it doesn't detect the input as having a value.
In the below example, timeSelector is the input with type="time".
if (timeSelector.value == "") {
timeSelector.classList.add("empty");
} else {
timeSelector.classList.remove("empty");
}
Is there any way to detect this type of thing?
To clarify, since apparently I didn't ask my question clearly enough, I need to detect when a time input has something entered, even if that something is an invalid or incomplete input.
Well the problem with html5 inputs is they do not give the text in the input if it is not valid. So you can use checkValidity when the user removes focus from the element.
var checkInput = function() {
var value = this.value
var isValid = this.checkValidity()
if (!this.value.length && isValid) {
console.log('empty');
} else if (!this.value.length && !isValid) {
console.log('invalid time entered')
} else {
console.log('valid time entered')
}
}
var input = document.querySelector("input")
input.addEventListener("input", checkInput)
input.addEventListener("blur", checkInput)
<input type="time" />
Per the specification on Input Elements with type time ( HTML Spec ) :
The value attribute, if specified and not empty, must have a value that is a valid time string.
If the value of the element is not a valid time string, then set it to the empty string instead.
This means that input and change events don't occur until the entire time field has been filled out. Why? Because nothing really has changed.
You may think that you can circumvent this by using keydown or keyup events, but this is simply not the case.
The value is not changed and is therefore inaccessible until a full string that is capable of being parsed as a time is inside the time input box.
By filling in the below example you can see how the events fire. Notice the lack of value until everything is filled in.
let i = document.querySelector("input"),
on = type => i.addEventListener(type, function() { console.log(`${type}, value: ${i.value}`); });
on("keydown");
on("keyup");
on("change");
on("input");
<input type="time">
The only way to possibly get around the lack of a changing value is to set a default value as below:
let i = document.querySelector("input"),
on = type => i.addEventListener(type, function() { console.log(`${type}, value: ${i.value}`); });
on("change");
<input type="time" value="00:00">
However, with a default value there is a risk that the user will submit a time that isn't something that you'd likely want.
You could write some validation code to take care of this depending on the complexity of your functionality this may be possible.
Overall if this is something you need and the functionality is a bit more complicated than you think you can handle validating yourself, it would be best to either create your own time input interface from other input types, or to use a library or UI kit from a source that has already done the legwork.

How to check for the multiple dots and stop to enter multiple dot using javascript?

I am having a input type text.
<input type="text" class="checkForDot" />
What i am trying to do is, when a user enters numbers into the box then find for the "." in the field, if it contains more then one ".", then prevent it to enter another "." in the text field.
my jquery code is:
$(".checkForDot").on("keyup", function (event) {
CheckForDot($(this).val());
});
function CheckForDot(value) {
if (value != null || value != '') {
var str = value.toString();
if (str.indexOf('.', str.indexOf('.') + 1) != -1) {
console.log("ok");
}
}
}
It is working fine, if two "." enters into the text box, but how to prevent to enter multiple "." in the text field?
If any other approach better than this please tell.
$(document).ready(function() {
var original='';
$('.checkForDot').on('input', function() {
if ($(this).val().replace(/[^.]/g, "").length > 1){
$(this).val(original);
}else{
original = $(this).val();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' class='checkForDot' />
Try to use this regex to find how many dots you got in string.
If you are looking to make a field that only allows for numbers, you should consider using an input of type="number" as they will only allow for valid number characters to by added to its value. In some cases, it might even bring a different visual keyboard to ease of filling, wich is better for accessibility and UX. The number input field will, by default allow for mutliple dots, wich is annoying and is a bit harder to prevent than in a text field so it's a case of figuring wether accessibility and your UX is more important than adding a few extra lines of Javascript.
A lot of people will tell you that it is bad practice to limit keyboard actions, and they are right. when you do a preventDefault() on everything but numbers and ".", you disable tabing through form fields, the browser alt menu, any ctrl shortcuts, anything that happens within the browser.
This solution is simple and will only allow one dot in the number field. It doesn't prevent from clicking back in the number and adding numbers before the ".". It doesn't prevent from executing browser keyboard shortcuts like refresh, copy and pasting, as long as the pasted value is a valid number. It will allow to add "." withing the body of the number.
The only behavior that can't be prevented is if the user press the dot key at the end of the input repeatedly, the dot will blink on and off. This happens because of the way the number field handles its value. Wen the user types a dot at the end of a number like "13.", javascript can only retreive "13" when looking at its value as long as no decimal number have been placed. If the user typed a dot again, the value of "13.." would not be a valid number and therefore javascript woudl retreive "". This ensure you eighter get a valid number or nothing at all. In my solution, if a value returns "" without the press of backspace, delete or cut, it gets rolled back to the last valid value, wich in my example was "13", obtained from the typed value "13.". Preventing this behavior seems practically impossible and isn't a deal breaker as you get ensured your field value is always a valid, single dot number.
let lastValidInputValue;
let selectedDot = false;
const onKeypress = (e) => {
if (e.key === "." && e.target.value.indexOf(".") !== -1 && !selectedDot) e.preventDefault();
selectedDot = false;
};
const onInput = (e) => {
if (e.target.value !== "") {
lastValidInputValue = e.target.value;
} else if (e.inputType.match(/delete/g)) {
lastValidInputValue = "";
} else {
e.target.value = lastValidInputValue;
}
};
const onSelect = (e) => {
selectedDot = (window.getSelection().toString().indexOf(".") > -1)? true : false;
}
<input type="number" id="myNumber" name="myNumber" step="any" onkeypress="onKeypress(event)" oninput="onInput(event)" onselect="onSelect(event)">
You can find very detailed comments and extra bits in this Codepen

Only-numerics in Input

I currently have a snippet that only allows numbers to be typed into an input:
$('input').bind('keypress', function(event) {
var charCode = event.which;
var keyChar = String.fromCharCode(charCode);
return /[0-9]/.test(keyChar);
});
jsFiddle: http://jsfiddle.net/wgsPr/
How can I adjust this to prevent typing in numbers greater than 500?
For example, if a user types 50, then types a 1 after, it won't display the 1. However if the user types a 0 after, it will display 500. And the same goes for if a user tries to type 968 it will not show the 8, it will only show 96.
Hopefully this makes sense.
The line would be
return /\d/.test(keyChar) && parseInt(this.value+keyChar, 10) <= 500;
(Demo)
However, I still suggest not to hook on and preventDefault of keypress events - go for keyup and change events and show error messages if the input's value is invalid. Or use a HTML5 <input type="number" /> with min and max attributes.
You really should not use such methods. This works far better:
<input type="number" min="0" max="500" />
However, if you insist, take your existing code and replace the return line with:
return /\d/.test(keyChar) && this.value <= 500;
if ($(this).val() > 500) {
$(this).val($(this).val().substr(0, $(this).val().length - 1));
return false;
}
I went ahead and attempted to solve this myself, which works. Basically, it checks the value and remove the last character in the case that it makes the entire input value larger than 500. Please let me know if anything should be modified.

Jquery limit text in text field copy safe

Here is a mind Boggling question i am having trouble with. I have a text field. This text field needs to accommodate U.S mobile numbers with 4 formats
XXX-XXX-XXXX
XXXXXXXXXX
X-XXX-XXX-XXXX
XXXXXXXXXXX
When the last character is entered it needs to do a check via ajax which i have no problem with.
I need to check if the textbox has the full mobile number in when typing, copying and pasting, deleting and every possible way to put numbers in that field.
i tried checking it with $("#id").keyup but that doesn't work when you paste something.
is there a way to check either via interval or something else if there is 10 or eleven characters in that field regardless of how it got there? [edit]
Here is a solution i found
var checkMsisdnInterval = window.setInterval( function () {
var msisdn = getdigits($("#newSessionMsisdn").val());
if(msisdn.length == 10 && !checked) {
doPreCheck(msisdn);
checked = true;
} else if(checked == true) {
//do something here
} else {
//do something else
}
}, (1000 * 60 * 0.1));
$("#newSessionMsisdn").keyup(function(){
checked = false;
});
function getdigits (s) {
return s.replace (/[^\d]/g, "");
}
it works like a bomb. Thanks for all the replies
Why not checking it in the ajax call, use the beforeSend method and check the length of the input field.
For your reference, http://api.jquery.com/jQuery.ajax/
Using jQuery, have you looked at the change event?
http://api.jquery.com/change/

How do I validate entry before input value is set?

I'm having a really strange problem. Here's my current Javascript:
jQuery('.highlightableTDCell input').keydown(function () {
var val = jQuery(this).val();
if (!GridView.prototype.validateStandardCellNumberFormat(val)) {
return false;
}
else return true;
});
When I use this, I can still get away with entering an illegal character, but no more than that. I'm really confused because I thought this would happen first.
Inside of the keydown event, the element.value has not yet been updated to account for the key that is currently being pressed. If you want to stop the key from hitting the input box, you need to interrogate the event.which and see if it is a key you want to allow or not.
The event is raised before the new content entered the input (letting you cancel the default behavior.)
You can use something like this, to get the new content:
$('.highlightableTDCell input').keypress(function(e){
var temp = this.value + String.fromCharCode(e.which)
return GridView.prototype.validateStandardCellNumberFormat(temp)
});
Note that it's not full proof. like when the user entered the new char in the middle of the input.
Validation should be done only on blur. With HTML5 it should be better, but not all browsers support it yet.
Tip: this.value == jQuery(this).val() There is no need to create jQuery object to get the value

Categories

Resources