Javascript phone number validation - javascript

I need to validate a phone number in javascript.
The requirements are:
they should be 10 digits, no comma, no
dashes, just the numbers, and not the
1+ in front
this is what I wrote so far
function validatePhone(field,alerttxt) {
with (field) {
if(value.length > 10) {
alert(alerttext);
return false;
}
for(i = 0; i < value.length; i++) {
if(parseInt(value[i]) == NaN) {
alert(alerttxt);
return false;
}
}
return true;
}
}
function validateForm(thisform) {
if (validatePhone(phone,"Invalid phone number")==false) {
phone.focus();
return false;
}
}
}
<form action="post.php" method="post" id="contactform" onsubmit="return validateForm(this)">
<ol>
<label for="phone">Your phone <span class="red"></span></label>
<input id="phone" name="phone" class="text" />
</li>
</ol>
</form>
but, obviously it doesn't work.
How can I write the validatePhone() function so that it works?

phone = phone.replace(/[^0-9]/g, '');
if(phone.length != 10) {
alert("not 10 digits");
} else {
alert("yep, its 10 digits");
}
This will validate and/or correct based on your requirements, removing all non-digits.

Google's libphonenumber is very helpful for validation and formatting of phone numbers all over the world. It is easier, less cryptic, and more robust than using a RegEx, and it comes in JavaScript, Ruby, Python, C#, PHP, and Objective-C flavors.

You could use Regular Expressions:
function validatePhone(field, alerttext) {
if (field.match(/^\d{10}/)) {
return true;
}
alert(alerttext);
return false;
}

Code to except only numbers braces and dashes
function DoValidatePhone() {
var frm = document.forms['editMemberForm'];
var stripped = frm.contact.value;
var isGoodMatch = stripped.match(/^[0-9\s(-)]*$/);
if (!isGoodMatch) {
alert("The Emergency Contact number contains invalid characters." + stripped);
return false;
}
}

Fixed function:
function validateForm(thisform) {
if (validatePhone(thisform.phone,"Invalid phone number")==false) {
thisform.phone.focus();
return false;
}
return true;
}

Add the pattern in which format you want directly in input tag.
<input id="phone" name="phone" pattern="\d{10}" class="text" />

Related

Javascript Condition : Real time validation

Can anyone please help me fix my javascript condition.
The scenario is this.
When I input 9 digit, label should turn red. But if the field is empty and i input 10 digit, label should turn blue. Im having a hard time to fix this.
function validateField(testField)
{
var reg2 = /^([\d])/;
if(testField.value.length > 0)
{
if(reg2.test(testField) == false)
{
document.getElementById("testlabel").style.color="red"
return false;
}
else
{
document.getElementById("testlabel").style.color="black"
return true;
}
}
else
{
document.getElementById("testlabel").style.color="blue";
return true;
}
}
<label id="testlabel">Test101: </label>
<input name="txtNum" type="text" id="Num" pattern=".{10,}" minlength="10" maxlength="10" onblur="validateField(this);" >
There are multiple issues with your code
Regex - If you need to validate the Regex for having 10 digits only then you can use the Regex \d{10}. Your Regex ^([\d]) only matches a digit at the start of the string.
reg2.test(testField) should be changed to reg2.test(testField.value), you are trying to compare the TextBox value and not the textbox itself.
function validateField(testField)
{
var reg2 = /\d{10}/;
if(testField.value.length > 0)
{
if(reg2.test(testField.value) == false)
{
document.getElementById("testlabel").style.color="red"
return false;
}
else
{
document.getElementById("testlabel").style.color="blue"
return true;
}
}
else
{
document.getElementById("testlabel").style.color="black";
return true;
}
}
<label id="testlabel">Test101: </label>
<input name="txtNum" type="text" id="Num" pattern=".{10,}" minlength="10" maxlength="10" onblur="validateField(this);" >

Can anyone help me with JavaScript form validation?

I have created a validate function using JavaScript. I need a validation that tests that password field in a form to make sure it is:
At least 8 characters.
Contains a numeric value.
Contains an alphabetic value.
I just need an If statement inside my validate function
function Validate()
{
with(document.memberInfo) {
evt = new userInfo(username.value, password.value, email.value, firstname.value, lastname.value, age.value, description.value);
}
with(evt)
{
if((email.indexOf("#",0)==-1))
{
alert("The email must contain the # symbol.");
return false;
}
evt.printEvent();
}
return true;
}
using regx function you can validate ur form . here is the code .
var xstr="^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$";
var str=Document.getElementById("id").value;
var ck=xstr.exec(str);
if(!ck || ck[0]!=str){
//code
}
you can use regex "/^(?=.*[0-9])(?=.*[a-zA-Z]).{8,}$/" refer this link stackoverflow
JsFiddle
var regex = /^(?=.*[0-9])(?=.*[a-zA-Z]).{8,}$/;
function getValue() {
return document.getElementById("myinput").value;
}
function test() {
alert(regex.test(getValue()));
}
function match() {
alert(getValue().match(regex));
}
<input type="text" id="myinput" value="vexillology"/>
<button id="testBtn" onclick=test()>test</button>
<button id="matchBtn" onclick=match()>match</button>
Using regex is the way to go, but the more readable solution is probably:
function isValid(pass) {
return pass.length >= 8 && // at least 8 characters
/\d/.test(pass) && // contains a digit
/[A-Za-z]/.test(pass); // contains a letter
}
function isValid(pass) {
return pass.length >= 8 &&
/\d/.test(pass) &&
/[A-Za-z]/.test(pass);
}
var field = document.getElementById("password");
var output = document.getElementById("output");
field.onkeyup = function() {
output.innerHTML = isValid(field.value) ? "Valid" : "Not Valid";
}
<input type="text" id="password" placeholder="Enter password" />
<span id="output"></span>
Alternatively, you can put it all in one regex:
function isValid(pass) {
return /^(?=.*[A-Za-z])(?=.*\d).{8,}$/.test(pass);
}
JSFiddle

Check the length of the number entered in a textbox

I want to write in text box and check if is integer and less than 16 numbers. I have the following JavaScript codes.
<script type="text/javascript">
function doCheck(field) {
if (isNaN(document.getElementById(field).value)) {
alert('this is not a number');
document.getElementById(field).focus();
document.getElementById(field).select();
return false;
}
else {
return true;
}
}
</script>
<form method="post" action="" onsubmit="return doCheck('number');">
national id=<input type="text" name="nat" id="number">
<input type="submit" name="submit">
</form>
document.getElementById(field).value.length
you can find the length of string inside the text box using this
function doCheck(field) {
var len = document.getElementById("number").val().length;
if(parse.Int(document.getElementById(field).value) && len < 16) {
return true;
}
else {
alert('your alert');
document.getElementById(field).focus();
document.getElementById(field).select();
return false;
}
}
be sure you parse it as an integer.
function doCheck(field) {
var input_value = document.getElementById(field).value;
if(isNaN(input_value) || parseInt(input_value,10) != input_value || input_value.length < 16) {
alert('this is not a number');
document.getElementById(field).focus();
document.getElementById(field).select();
return false;
}
else{
return true;
}
}
isNAN() checks whether a number is an illegal number of any type, not only integer. So you have to use something else there, a regular expressions maybe.
To get the length of the field you can simply use:
document.getElementById(field).value.length

javascript validation numerical

Hi sorry i'm still pretty new to javascript.
I've developed a form in HTML and now i'm attempting to add javascript to validate the form.
So far i have simple javascript to make sure each element is filled in,
if (document.order.suburb.value=="")
{
alert("Suburb Cannot Be Empty")
return false
}
if (document.order.postcode.value=="")
{
alert("Postcode Cannot Be Empty")
return false
}
I then have javascript to validate the length of some of the elements,
if (document.order.telephone.value.length < 10)
{
alert("Invalid Telephone Number")
return false
}
Now i'm trying to validate numeric values in the telephone number part but it's not executing correctly, it's like the code is just ignored when it's being executed.
var digits="0123456789"
var temp
var i
for (i = 0 ; i <document.order.telephone.value.length; i++)
{
temp=document.order.telephone.value.substring(i,i+1)
if (digits.indexOf(temp)==-1)
{
alert("Invalid Telephone Number")
return false
}
}
Thanks for reading and thanks for the help :) been stuck on this issue for weeks and have no idea what i'm doing wrong, i tried to code on a separate document with another form and it seemed to work fine.
EDIT
Code for validation for digits in postcode
var post = document.order.postcode.value.replace(white,'');
if(!post){
alert("Post code required !");
return false;
}
post = post.replace(/[^0-9]/g,'');//replace all other than digits
if(!post || 4 > postcode.length) {
alert("Invalid Postcode !");
return false;
}
You may try this example:
var validate = function() {
var white = /\s+/g;//for handling white spaces
var nonDigit = /[^0-9]/g; //for non digits
if(!document.order.suburb.value.replace(white, '')) {
alert("Suburb required !");
return false; //don't allow to submit
}
var post = document.order.postcode.value.replace(white, '')
if(!post) {
alert("Post code required !");
return false;
}
post = post.replace(nonDigit,'');//replace all other than digits
if(!post || 6 > post.length) { //min post code length
alert("Invalid Post code !");
return false;
}
var tel = document.order.telephone.value.replace(white, '');
if(!tel) {
alert("Telephone required !");
return false;
}
tel = tel.replace(nonDigit,'');
if(!tel || 10 > tel.length) {
alert("Invalid Telephone !");
return false;
}
return true; //return true, when above validations have passed
};
<form onsubmit="return validate();" action="#" name="order">
Suburb: <input type="text" id="suburb" name="suburb" ><br/>
Post code: <input type="text" id="postcode" name="postcode"/><br/>
Telephone: <input type="text" id="telephone" name="telephone"/><br/>
<input type="reset"/><input type="submit"/>
</form>
Here is a FIDDLE that will give you something to think about.
You could handle this task in hundreds of ways. I've just used a regex and replaced all of the non-numbers with '' - and compared the length of two variables - if there is anything other than a number the length of the regex variable will be shorter than the unchanged mytelephone.
You can do all kinds of "validation" - just me very specific in how you define "valid".
JS
var mysuburb, mypostcode, mytelephone;
$('.clickme').on('click', function(){
mysuburb = $('.suburb').val();
mypostcode = $('.postcode').val();
mytelephone = $('.telephone').val();
console.log(mysuburb + '--' + mypostcode + '--' + mytelephone);
if(mysuburb.length < 1)
{
$('.errorcode').html('');
$('.errorcode').append('Suburb is required');
return false;
}
if(mypostcode.length < 1)
{
$('.errorcode').html('');
$('.errorcode').append('postode is required');
return false;
}
if( mytelephone.length < 1 )
{
$('.errorcode').html('');
$('.errorcode').append('telephone number is required');
return false;
}
if( mytelephone.length != mytelephone.replace(/[^0-9]/g, '').length)
{
$('.errorcode').html('');
$('.errorcode').append('telephone number must contain only numbers');
return false;
}
});

Javascript - validation, numbers only

I'm trying to get my login form to only validate if only numbers were inputted. I can it to work if the input is only digits, but when i type any characters after a number, it will still validate etc. 12akf will work. 1am will work. How can i get past this?
Part of the Login
<form name="myForm">
<label for="firstname">Age: </label>
<input name="num" type="text" id="username" size="1">
<input type="submit" value="Login" onclick="return validateForm()">
function validateForm()
{
var z = document.forms["myForm"]["num"].value;
if(!z.match(/^\d+/))
{
alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
}
}
Match against /^\d+$/. $ means "end of line", so any non-digit characters after the initial run of digits will cause the match to fail.
Edit:
RobG wisely suggests the more succinct /\D/.test(z). This operation tests the inverse of what you want. It returns true if the input has any non-numeric characters.
Simply omit the negating ! and use if(/\D/.test(z)).
here is how to validate the input to only accept numbers this will accept numbers like 123123123.41212313
<input type="text"
onkeypress="if ( isNaN(this.value + String.fromCharCode(event.keyCode) )) return false;"
/>
and this will not accept entering the dot (.), so it will only accept integers
<input type="text"
onkeypress="if ( isNaN( String.fromCharCode(event.keyCode) )) return false;"
/>
this way you will not permit the user to input anything but numbers
This one worked for me :
function validateForm(){
var z = document.forms["myForm"]["num"].value;
if(!/^[0-9]+$/.test(z)){
alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
}
}
Late answer,but may be this will help someone
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Use will be like
nn=document.forms["myForm"]["num"].value;
ans=isNumber(nn);
if(ans)
{
//only numbers
}
This ans was found from here with huge vote
Validate numbers in JavaScript - IsNumeric()
function validateNumber(e) {
const pattern = /^[0-9]$/;
return pattern.test(e.key )
}
<input name="username" id="username" onkeypress="return validateNumber(event)">
This approach doesn't lock numlock numbers, arrows, home, end buttons and etc
The simplest solution.
Thanks to my partner that gave me this answer.
You can set an onkeypress event on the input textbox like this:
onkeypress="validate(event)"
and then use regular expressions like this:
function validate(evt){
evt.value = evt.value.replace(/[^0-9]/g,"");
}
It will scan and remove any letter or sign different from number in the field.
No need for the long code for number input restriction just try this code.
It also accepts valid int & float both values.
Javascript Approach
onload =function(){
var ele = document.querySelectorAll('.number-only')[0];
ele.onkeypress = function(e) {
if(isNaN(this.value+""+String.fromCharCode(e.charCode)))
return false;
}
ele.onpaste = function(e){
e.preventDefault();
}
}
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
jQuery Approach
$(function(){
$('.number-only').keypress(function(e) {
if(isNaN(this.value+""+String.fromCharCode(e.charCode))) return false;
})
.on("cut copy paste",function(e){
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
The above answers are for most common use case - validating input as a number.
But to allow few special cases like
negative numbers & showing the invalid keystrokes to user before
removing it, so below is the code snippet for such special use cases.
$(function(){
$('.number-only').keyup(function(e) {
if(this.value!='-')
while(isNaN(this.value))
this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'')
.split('').reverse().join('');
})
.on("cut copy paste",function(e){
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
Regular expressions are great, but why not just make sure it's a number before trying to do something with it?
function addemup() {
var n1 = document.getElementById("num1");
var n2 = document.getElementById("num2");
sum = Number(n1.value) + Number(n2.value);
if(Number(sum)) {
alert(sum);
} else {
alert("Numbers only, please!");
};
};
function ValidateNumberOnly()
{
if ((event.keyCode < 48 || event.keyCode > 57))
{
event.returnValue = false;
}
}
this function will allow only numbers in the textfield.
I think we do not accept long structure programming we will add everytime shot code see below answer.
<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" >
Using the form you already have:
var input = document.querySelector('form[name=myForm] #username');
input.onkeyup = function() {
var patterns = /[^0-9]/g;
var caretPos = this.selectionStart;
this.value = input.value.replace(patterns, '');
this.setSelectionRange(caretPos, caretPos);
}
This will delete all non-digits after the key is released.
var elem = document.getElementsByClassName("number-validation"); //use the CLASS in your input field.
for (i = 0; i < elem.length; i++) {
elem[i].addEventListener('keypress', function(event){
var keys = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0];
var validIndex = keys.indexOf(event.charCode);
if(validIndex == -1){
event.preventDefault();
}
});
}
If you are using React, just do:
<input
value={this.state.input}
placeholder="Enter a number"
onChange={e => this.setState({ input: e.target.value.replace(/[^0-9]/g, '') })}
/>
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<script type="text/babel">
class Demo extends React.Component {
state = {
input: '',
}
onChange = e => {
let input = e.target.value.replace(/[^0-9]/g, '');
this.setState({ input });
}
render() {
return (
<div>
<input
value={this.state.input}
placeholder="Enter a number"
onChange={this.onChange}
/>
<br />
<h1>{this.state.input}</h1>
</div>
);
}
}
ReactDOM.render(<Demo />, document.getElementById('root'));
</script>
// I use this jquery it works perfect, just add class nosonly to any textbox that should be numbers only:
$(document).ready(function () {
$(".nosonly").keydown(function (event) {
// Allow only backspace and delete
if (event.keyCode == 46 || event.keyCode == 8) {
// 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) {
alert("Only Numbers Allowed"),event.preventDefault();
}
}
});
});
Avoid symbols like "." "," "+" "-". I tried it and it works fine.
$('#example').keypress(function (evt) {
if (evt != null && evt.originalEvent != null && /\D/.test(evt.originalEvent.key)) {
evt.preventDefault();
evt.stopImmediatePropagation();
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="example" id="example">

Categories

Resources