Max and Min for an Input - javascript

For this particular existing form there is an input to accept phone numbers. It already validates to only accept numbers and added a max character attribute for 10 characters.
However someone could add 1-9 digits. So I need to add javascript to check to make sure the character count for that field is 10. The input has an ID of phonenumber.
Can someone tell me how to modify the following code to make that work? Note: The "= 10 Characters" is just a placeholder, that part needs to be replaced with real code.
function checkEmail(theForm) {
if (theForm.getElementById("phonenumber").value = 10 Characters )
{
alert('Your phone number is not 10 digits.');
return false;
} else {
return true;
}
}

I think you want .length
if (theForm.getElementById("phonenumber").value.length == 10) {

You may want to be gentle with your users, and allow common conventions in phone numbers,
like spaces or dash-hyphens.
Just check for 10 digits.
When you use the value, remove any non digits.
function checkphone(v){
if(v.match(/\d/g).length==10) return true;
throw 'Phone number must have 10 digits';
}
checkphone('207 555-5555');

if (theForm.getElementById("phonenumber").value.length != 10)
...since you want something to happen if the length is not 10.

Verify min and max length of phone number field using Javascript Validation
function checkLimit() {
var x, text;
// Get the value of the input field with id="Phone"
phone = document.getElementById("Phone").value;
// If phone is Not a Number or less than 10 or greater than 10
if (isNaN(phone) || phone.length < 10 || phone.length > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("resp").innerHTML = text;
}
<input onkeypress="checkLimit()" id="Phone" name="Phone" type="number" class="form-control" placeholder="Phone Number" required="required"/>
<p id="resp"></p>

try this:
function checkEmail(theForm) {
if (theForm.getElementById("phonenumber").value.length != 10 )
{
alert('Your phone number is not 10 digits.');
return false;
} else {
return true;
}
}

Related

How can I count the number of digits of a number with leading zeros in javascript?

I am taking a field value, that should be a 4 digit number.
I want to make sure that the value is a 4 digit number and if not, have a pop up that says "enter a 4 digit number".
I noticed that when I put the field value into a variable it does not take any of the leading zeros. The last test case I ran the code with was a value of '0000'.
var relay = this.getField("RELAY NUM").value;
var relayString = relay.toString();
var relaySplit = relayString.split("");
console.println("relay= " + relay);
console.println("string= " + relayString);
console.println("split= " + relaySplit);
for(i = 0; i < 4; i++){
if (relaySplit[i] >= 0) {
console.println("Looks good so far");
} else {
console.println("Please enter 4 digit number");
}
}
--------------------------------------------------------
relay= 0
string= 0
split= 0
Looks good so far
Please enter 4 digit number
Please enter 4 digit number
Please enter 4 digit number
true
Instead of traversing arrays, an approach you may want to consider is using a regex to determine whether the input value meets your criteria. Then on events such as keyup (using jQuery here but not necessary), you run the validation and apply styles, or send forth the popups as you wish. I put a limit on the length of the input so users are not able to enter MORE then expected input, but this isn't necessarily needed.
$("#input").keyup(function() {
let input = $("#input").val()
let isValid = validate(input)
$("#val").text(isValid ? "Valid" : "Invalid")
})
function validate(val) {
let x = /^[0-9]{4}$/
return x.test(val)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="text" id="input" maxLength="4" />
<label id="val"></label>
</div>

Javascript Phone Validation

I want if phone number starts with + it should accept 12 digits if it does not contain + it should accept 10 digit what changes I have to do?
My code is attached below.
function phvalid()
{
var a = document.getElementById('phone').value;
var gb = /^([0|\+[0-9]{1,5})?([7-9][0-9]{9})$/;
if (a=="") {
document.getElementById('ph').innerHTML="Enter Number";
}
if (a.match(gb))
{
document.getElementById("ph").innerHTML="";
// return true;
}
if(a.length!=10)
{
document.getElementById("ph").innerHTML="Enter 10 digits";
return false;
}
if(a.indexOf("+")==0)
{
document.getElementById("ph").innerHTML="Enter 12 digits";
return false;
}
else
{
document.getElementById('ph').innerHTML="";
}
}
Hope this will help you..!! I have used the simple startwith method.
function phoneValidator() {
var number = document.getElementById('phoneNumber').value
if(number.startsWith("+")) {
document.getElementById("phoneNumber").maxLength = 12;
}
else {
document.getElementById("phoneNumber").maxLength = 10;
}
}
<input type="text" name="phoneNumber" id="phoneNumber" onkeyup="phoneValidator()"/>
Firstly, your check for 10 digits overrides your check for 12. What I would do is:
function phvalid()
{
let phone = document.getElementById('phone');
let regex = /^([0|\+[0-9]{1,5})?([7-9][0-9]{9})$/;
if (phone.value=="") {
phone.innerHTML="Enter Number";
}
if (phone.value.match(regex))
{
phone.value.innerHTML="";
// return true;
}
if ( phone.value.charAt(0) != '+' && phone.value.length != 12 ){
if ( phone.value.length != 10 ){
phone.innerHTML = "Please enter a valid phone number, it should be 10 digits unless it is international in which case it should be 12 prefixed by a +";
return;
} else {
// Do whatever you need to do for a 10 digit phone number
}
} else {
// Do whatever you need to do for a 12 digit number
}
}
It is always easier to read your code later if you explain what you are doing, to yourself. The nested if, yes you could do it all on one line or use an iif there but when you come back to read it later, this will probably be easier to understand. I also set the result of the document.getElementById to a variable for both less typing and to make it clear what you are modifying. Your code you are modifying a different element. If that's what you are trying to do, it is still easier than calling getElementById every time you wish to modify it, calling and storing it means you only have to change it in one place if your code changes later instead of having a weird bug because you forgot to change it somewhere.
If I'm reading your regex right, the 10 digit phone number must start with a 0? It might be better to use:
let regex=/(^\+?\d{10,12}$)/;

Javascript user input validation

My exercise is to force a user to type a number and check that it is less than 100. I think I've done this well but there is another case I don't know how to do. If the user does not type any number in the space, the program should show something like "you must type a number". How should I write the code?
var number=prompt('enter a number');
if (number<100){
newnumber=100-number;
document.write(number+'is less than 100 by'+ newnumber);
}else if(number>100){
document.write('type again');
}
You can determine if the users input is a valid number by using the isNaN function. I have also validated the blank character for you, as shown below.
var isValid = !isNaN(number) && number !== "";
Full snippet:
var number = prompt('enter a number');
number = number.replace(/\s/g, "");
var isValid = !isNaN(number) && number !== "";
if (isValid) {
if (number<100) {
newnumber=100-number;
document.write(number+'is less than 100 by'+ newnumber);
} else if(number>100) {
document.write('type again');
}
} else {
document.write("Looks like you didn't enter a valid number");
}
https://jsfiddle.net/ezgn5cv5/
var number = null;
while (number !== 0 && !number || number >= 100) {
number = parseInt(prompt('Enter a number, less than 100'));
}
document.write(
number +
' is less than 100 by ' +
(100 - number)
);
This puts us in a loop for whether or not the number is a valid integer (I assumed that's what you wanted, but you could change this to float or something else), and under 100. Only when the user's input is valid will it go to the line to output.
The second condition for the while loop is !number. This basically tests for falsy conditions, such as NaN or null. If parseInt() can't figure out what the user typed in for a number, it will return NaN. And, of course, we initialized the number variable to null.
The first condition for while is number !== 0 is actually required because of the second condition which tests for falsy. 0 is falsy, but 0 is a valid number less than 100, so we need to make sure that we let 0 be valid. Conditionals like these short circuit. That means that they are processed from left to right, and any condition failing the test will immediately bypass the conditional block of code below. If number is 0, we know that the whole condition is false and we can move on.
The third condition simply ensures we're under 100 by re-prompting if we're not.
Also, I should note that document.write() has some issues. It's better to select an element on the page and set its text.
Remove all spaces .replace(/\s/g, "").
Detect if user input a number using parseFloat() if you want to allow
user to input decimal numbers like 5.254 or only integers using
parseInt() like 5.
Then detect if number > 100 or number < 100.
See this example:
var number = prompt('enter a number');
number = number.replace(/\s/g, ""); //remove all spaces
if (number != "") { // if not empty
if (parseFloat(number) == number) { // if decimal/integer number
if (number < 100) {
newnumber = 100 - number;
document.write(number + ' is less than 100 by ' + newnumber);
} else if (number > 100) {
//number = prompt('enter a number');
document.write('type again');
}
} else {
//number = prompt('enter a number');
document.write('you must type a number');
}
} else { // if empty input
//number = prompt('enter a number');
document.write('shouldn\'t be empty');
}

how to validate cell number

i have to validate the cell no and my requirements are :
1.filed must not empty
2. if user enter alphabetic value it pop-up "alphabets are not allowed"
3. field must start with "+" sign
4. if filed value is less than 13 it pop-up "please enter valid phone no"
i am using this code..
function validateForm()
{
var cell = document.reg_form.cellno.value;
if(cell.length==0)
{
alert("Please enter cell number");
reg_form.cellno.focus();
return false;
}
if(isNaN(cell)||cell.indexOf(" ")!=-1)
{
alert("Enter numeric value")
return false;
}
if (cell.charAt(0)!="+")
{
alert("Cell no should start with +");
return false
}
if(cell.length < 13)
{
alert("You have entered wrong number");
reg_form.cellno.focus();
return false;
}
return true;
}
some code is not working here
when i enter numeric value.. it shows {"Cell no should start with "+"}
when i put {+} sign it says please enter numeric value
when i enter only single numeric value like {9} it goes forward.. although in this way field has only 2 value "+" and "9".. it should pop-up {"You have entered wrong number"}
please tell me where i made the mistake....
Your comparison of the cell length with 13 returns true (and alerts) if the value is longer than 13. I suspect you wanted
if(cell.length < 13)
A regular expression that matches only a plus sign and 12 digits:
function validateForm(){
var cell = document.reg_form.cellno;
return /^\+\d{12}$/.test(cell.value);
}
function validateForm()
{
var cell=document.reg_form.cellno.value;
var msg="";
if(cell.length==0)
{
msg="Please enter cell number";
alert(msg);
reg_form.cellno.focus();
return false;
}
if(isNaN(cell)) msg+="\nEnter numeric value";
if (cell.charAt(0)!="+") msg+="\nCell no should start with +";
if(cell.length != 13) msg+="\nCell number must be within 13 characters";
if(msg)
{
alert((msg));
reg_form.cellno.focus();
return false;
}
return true;
}
An example is here.

Check If only numeric values were entered in input. (jQuery)

I would like to check if users enter correct phone number in, with help of jQuery, so far I got to this stage:
var phone = $("input#phone").val();
if (phone !== "") {
//Check if phone is numeric
$("label#phone_error").show(); //Show error
$("input#phone").focus(); //Focus on field
return false;
}
Basically it checks if phone number was entered and if it was, I would like to check if it is a numeric value and if it is not display the error messages.
Could anyone help with checking if it is numeric?
Try this ... it will make sure that the string "phone" only contains digits and will at least contain one digit
if(phone.match(/^\d+$/)) {
// your code here
}
There is a built-in function in jQuery to check this (isNumeric), so try the following:
var phone = $("input#phone").val();
if (phone !== "" && !$.isNumeric(phone)) {
//Check if phone is numeric
$("label#phone_error").show(); //Show error
$("input#phone").focus(); //Focus on field
return false;
}
You can use jQuery method to check whether a value is numeric or other type.
$.isNumeric()
Example
$.isNumeric("46")
true
$.isNumeric(46)
true
$.isNumeric("dfd")
false
I used this to check if all the text boxes had numeric values:
if(!$.isNumeric($('input:text').val())) {
alert("All the text boxes must have numeric values!");
return false;
}
or for one:
$.isNumeric($("txtBox").val());
Available with jQuery 1.7.
http://docs.jquery.com/Plugins/Validation/CustomMethods/phoneUS
Check that out. It should be just what you're looking for. A US phone validation plugin for jQuery.
If you want to do it on your own, you're going to be in for a good amount of work. Check out the isNaN() function. It tells you if it is not a number. You're also going to want to brush up on your regular expressions for validation. If you're using RegEx, you can go without isNaN(), as you'll be testing for that anyway.
I used this:
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
if (!(/^[-+]?\d*\.?\d*$/.test(document.getElementById('txtRemittanceNumber').value))){
alert('Please enter only numbers into amount textbox.')
}
else
{
alert('Right Number');
}
I hope this code may help you.
in this code if condition will return true if there is any legal decimal number of any number of decimal places. and alert will come up with the message "Right Number" other wise it will show a alert popup with message "Please enter only numbers into amount textbox.".
Thanks... :)
for future visitors, you can add this functon that allow user to enter only numbers: you will only have to add jquery and the class name to the input check that into http://jsfiddle.net/celia/dvnL9has/2/
$('.phone_number').keypress(function(event){
var numero= String.fromCharCode(event.keyCode);
var myArray = ['0','1','2','3','4','5','6','7','8','9',0,1,2,3,4,5,6,7,8,9];
index = myArray.indexOf(numero);// 1
var longeur= $('.phone_number').val().length;
if(window.getSelection){
text = window.getSelection().toString();
} if(index>=0&text.length>0){
}else if(index>=0&longeur<10){
}else {return false;} });
I used this kind of validation .... checks the pasted text and if it contains alphabets, shows an error for user and then clear out the box after delay for the user to check the text and make appropriate changes.
$('#txtbox').on('paste', function (e) {
var $this = $(this);
setTimeout(function (e) {
if (($this.val()).match(/[^0-9]/g))
{
$("#errormsg").html("Only Numerical Characters allowed").show().delay(2500).fadeOut("slow");
setTimeout(function (e) {
$this.val(null);
},2500);
}
}, 5);
});
This isn't an exact answer to the question, but one other option for phone validation, is to ensure the number gets entered in the format you are expecting.
Here is a function I have worked on that when set to the onInput event, will strip any non-numerical inputs, and auto-insert dashes at the "right" spot, assuming xxx-xxx-xxxx is the desired output.
<input oninput="formatPhone()">
function formatPhone(e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
e.target.value = !x[2] ? x[1] : x[1] + '-' + x[2] + (x[3] ? '-' + x[3] : '');
}

Categories

Resources