Validating phone number with JavaScript - javascript

I have a form with three elements. I want to validate the phone number when the user enters it. If the user moves to the next element and phone number contains and characters which is not numbers I want to display an alertbox.
I have written some code but am completely stumped. The problem I am having with my function is, that even if I enter only numbers into the phone number element I still get the alert box displayed. My code looks like this:
<script type="text/javascript">
function validateForm()
{
checkNr= isNaN(document.forms[0].elements[1])
if(checkNr == true)
{
window.alert("You can only enter numbers. Please try again")
}
}
</script>
<form>
<strong>FULLNAME: </strong><input type="text" / id="name"><br />
<strong>PHONE NR: </strong><input type="text" id="phone" onblur="validateForm()" />
<strong>NATIONALITY</strong><input type="text" id="nat" /><br />
<input type="button" id="subButton" onclick="calc()" value="Submit" />
</form>
Thank you in advance for all your answers and help.

Change
document.forms[0].elements[1]
to
document.forms[0].elements[1].value
You were testing the element itself, not the element's value.
jsFiddle example
BTW, if someone enters a phone number with a dash or parenthesis (e.g. (555) 123-4567) what do you expect to happen?

Here you will find many exemple to achieve your goal :
for example if you can use only number :
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}

You should do it with a regular expression. See here:
A comprehensive regex for phone number validation
Validate phone number with JavaScript

Related

How To Validate Form Field Using Javascript

I am trying to validate my form phone field to prevent users from entering the same numbers in my javascript.
If the number provided by the user matches with the same numbers in my javascript, They will get a warning and the form would not submit.
However, I noticed that my code below shows the warning whether the numbers match or not.
I need corrections to know what I am doing wrong. Thanks.
Code below;
$('.validate').hide();
$('body').on('blur', '#phone', function() {
$('.validate').hide();
isphone($(this).val());
});
function isphone(phone) {
if (phone === "1234" || phone === "23456"){
$(".validate").show();
} else {
$(".validate").hide();
}
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<form action='' method='POST' id="submitForm" >
<input type="phone" name='phone' required='' id="phone" placeholder="0000-000-0000"/>
<div class="validate"><span style="color: red;"><b>Please enter a valid phone!</b></span></div>
<button href='/' type='submit' id="submitForm">Process</button>
</form>
I believe this should work.
I move the changes for hiding and showing $('.validate') to the isphone function, and removed that done variable that wasn't doing anything useful (used if...else instead).
Also, don't use document.getElementById if you're already using JQuery.
$('.validate').hide();
$('body').on('blur', '#phone', function() {
$('.validate').hide();
isphone($(this).val());
});
function isphone(phone) {
if (phone === "1234" || phone === "23456"){
$(".validate").hide();
} else {
$(".validate").show();
}
}

regex jquery for IDnumber if match then enable button

i don't know much regex so if some one can help me with this it would be great i have a input box and a button.
if the user enters A12345678 the first character should always be A and the rest should always be numbers and altogether it should have less then 10 characters
<input type="textbox" id="id" />
<input type="submit" id="submit" />
<script type="text/javascript">
/*Check if ID is correct */
$('#id').keyup(function(){
var id= $(this).val();
if(id == /*'A12345678' */{
//enable button
}else{
// disable button
});
</script>
i would appreciate if some one could help me out a bit with this
Here ya go ^(A\d{1,9})$;
^ will start the verification at the beginning of the string
() encapsulates your result. not necessarily needed, but I like to have them
A will match the uppercase character
\d{1, 9} will match 1 to 9 numbers following the letter A
$means the end of the string
Use:
if(id.match(/^(A\d{1,9})$/)) {
// do stuff
}
Hope this helps.
Watch it work: https://jsfiddle.net/ppmr12v6/

jQuery Click Function, input value length and pattern

I have a problem, that I'm struggling with since 2 days.
I have a webpage that asks for the phone number, and I'm trying to make a "validator" for the phone number into the input tab, but it seems that I cannot figure out how to check the minlength for the input tab, neither how to accept only numerical characters. Here's the code:
$("#start").click(function(){ // click func
if ($.trim($('#phonenr').val()) == ''){
$("#error").show();
I tried adding:
if ($.trim($('#phonenr').val()) == '') && ($.trim($('#phonenr').val().length) < 15)
But it just won't work.
Any help would be appreciated. Also please tell me how can I make it allow only numbers?
Thank you!
Final code, with help of #Saumya Rastogi.
$("#start").click(function(){
var reg = /^\d+$/;
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$("#error").show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$("#error").show();
} else {
You can make your validation work.
You can use test (Regex Match Test) for accepting only digits in the input text. Just use javascript's substring to chop off the entered non-digit character like this:
$(function() {
$('#btn').on('click',function(e) {
var reg = /^\d+$/; // <------ regex for validatin the input should only be digits
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$('label.error').show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$('label.error').show();
} else {
$('label.error').hide();
}
});
})
label.error {
display: none;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="phonenr" type="text" value=""><br>
<label class='error'>Invalid Number</label>
<br><br>
<button id="btn">Click to Validate</button>
Hope this helps!
If you are using HTML5, then you can make use of the new number input type available
<input type="number" name="phone" min="10" max="10">
You can also use the pattern attribute to restrict the input to a specific Regular expression.
If you are looking for the simplest way to check input against a pattern and display a message based on validity, then using regular expressions is what you want:
// Wait until the DOM has been fully parsed
window.addEventListener("DOMContentLoaded", function(){
// Get DOM references:
var theForm = document.querySelector("#frmTest");
var thePhone = document.querySelector("#txtPhone");
var btnSubmit = document.querySelector("#btnSubmit");
// Hook into desired events. Here, we'll validate as text is inputted
// into the text field, when the submit button is clicked and when the
// form is submitted
theForm.addEventListener("submit", validate);
btnSubmit.addEventListener("click", validate);
thePhone.addEventListener("input", validate);
// The simple validation function
function validate(evt){
var errorMessage = "Not a valid phone number!";
// Just check the input against a regular expression
// This one expects 10 digits in a row.
// If the pattern is matched the form is allowed to submit,
// if not, the error message appears and the form doesn't submit.
!thePhone.value.match(/\d{3}\d{3}\d{4}/) ?
thePhone.nextElementSibling.textContent = errorMessage : thePhone.nextElementSibling.textContent = "";
evt.preventDefault();
}
});
span {
background: #ff0;
}
<form id="frmTest" action="#" method="post">
<input id="txtPhone" name="txtPhone"><span></span>
<br>
<input type="submit" id="btnSubmit">
</form>
Or, you can take more control of the process and use the pattern HTML5 attribute with a regular expression to validate the entry. Length and digits are checked simultaneously.
Then you can implement your own custom error message via the HTML5 Validation API with the setCustomValidity() method.
<form id="frmTest" action="#" method="post">
<input type="tel" id="txtPhone" name="txtPhone" maxlength="20"
placeholder="555-555-5555" title="555-555-5555"
pattern="\d{3}-\d{3}-\d{4}" required>
<input type="submit" id="btnSubmit">
</form>
Stack Overflow's code snippet environment doesn't play well with forms, but a working Fiddle can be seen here.

Referencing the length of a HTML number form element?

I have a form that takes numbers, and there is a specific (Phone number, or phNo) form element that I want to only accept 7 digits in length (no more, no less). Using Javascript the Idea is:
If element length not equal to 7: true else false
Here is my code:
var phNo = document.getElementsByName('phNo'); //here I try to get
the form value in the form of an object. This is where I think I am going wrong
var phNoString = phNo.toString(); //Not to sure if I need this line or not, read somewhere that .length only works on a string
if(phNoString.length != 7) {
//Do something for false
return;
} else {
//Do something for true
}
<form id="myForm" action="form_action.asp">
First name: <input type="text" name="fName"><br>
Last name: <input type="text" name="lName"><br>
Phone Number: <input type="number" name="phNo" max="7"><br>
Credit Card Number: <input type="number" name="cardNo"><br>
</form>
<input id="submit" type="button"value="Submit"onClick="detailsSubmit()">
var phNoString = phNo.toString();
This line will return [object HTMLInputElement], you need to use phNo.value if you want the value the user typed inside the input.
Not really related to the problem, but <input type="number" name="phNo" max="7"> here the max attribute only means the highest number possible in that input is 7. Using a browser that supports html5 inputs it's giving me an invalid highlight if I try to enter any phone number.
I would change it to a simple text field and use the maxlength attribute, which is probably what you intended;
<input type="text" name="phNo" maxlength="7">
"getElementsByName" returns a collection type, you should be doing like this to read the value from the element.
var phNoString = document.getElementsByName('phNo')[0].value;
if(phNoString.toString().length != 7) {
//Do something for false
return;
} else {
//Do something for true
}
If you did decide to leave it as a number input, you don't need to convert it to a string. Phone Numbers can't start with 0, so the smallest number would be 1000000. If your input has a max of 7, then you can check that the value is greater than that.
var phNoString = document.getElementsByName('phNo')[0].value;
if(var phNoString > 1000000){
// truthy
}else{
// falsey
}
The document.getElementsByName() function is depreciated in HTML5. See note in w3school site. Use document.getElementById() instead and add an ID tag to your phone input control.
Also use input type="tel" for your phone numbers. That way the browsers, especially on mobile devices, know how to correctly display the inputted value on the screen.
Finally, note the use of regular expressions to do a validation check on the inputted phone number. Also, it is important to note, the HTML5 regex validation runs after the JavaScript function executes. Below is a code snippet that you can sink your new developer teeth into:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<form>
Phone Number (format: xxx-xxx-xxxx):: <input type="tel" id="phNo" name="phNo" pattern="^\d{3}-\d{3}-\d{4}$"/><br>
<button type="submit" name="submit" onclick="checkphonelength()">submit</button>
</form>
<script type="text/javascript">
function checkphonelength(){
var phNoStringLength = document.getElementById('phNo').value.length;
if(phNoStringLength === 12) {
alert("true");
return true;
}
alert(false);
return false;
}
</script>
</body>
</html>

JavaScript empty field validation does not work

So, I have a number textbox and I want to validate it using JavaScript. If the user has not input any number, it will prompt him/her to enter one. My codes below:
<input type="number" autofocus id="lol"/>
<input type="button" onClick="validate()" value="Input"/>
<script>
function validate() {
var numfield = document.getElementById("lol").value;
if ( numfield == "") {
document.write("Missing number!");
}
</script>
What is wrong?
You have missed a } at the end of the script. With that fixed, it works normally.
Try to use length property.
if ( numfield.length > 0) {
...
}

Categories