how to validate cell number - javascript

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.

Related

Validating all letters in field with JavaScript not working?

function validate() {
var forename = document.getElementById('forename').value;
var alpha = /^[a-zA-Z\s]+$/;
var num = /^[0-9]+$/;
var space = " ";
if (forename == "") {
alert("Please fill out the First Name field.");
return false;
}
if (forename.indexOf(" ") > -1) {
alert("No spaces are allowed in the First Name field.");
return false;
}
if (forename.value.match(num)) {
alert("No numbers are allowed in the First Name field.");
return false;
}
The above code is part of a validation function for a registration form.
For whatever reason I cannot get my all letters/all numbers if statements to work. Without them the form processes perfectly, however when I start including any value.match argument it breaks the function from that point on. Am I missing anything obvious here?

How to avoid to enter repeated number in input text form?

I'm trying past few days to solve input number form validation in javascript. The logic user doesn't allow to enter repeated same number like "00000000000", "11111111111". If they enter numbers on text field i have to show error message,
sample code,
var mobNumber = $('#phNo').val();
if(mobNumber.match("00000000") || mobNumber.match("1111111")) {
alert('Please enter valid phone number');
}
You could use following regex ^(\d)\1+$ :
^ asserts position at start of the string
(...) 1st capturing group
\d matches a digit (equal to [0-9])
\1 matches the same text as most recently matched by the 1st capturing group
+ Quantifier, matches between one and unlimited times, as many times as possible, giving back as needed
$ asserts position at the end of the string, or before the line terminator right at the end of the string (if any).
See following example:
function test(par){
if(par.match(/^(\d)\1+$/g)){
console.log(par + " is not valid");
}else{
console.log(par + " is valid");
}
}
test("11111111");
test("11131111");
test("111a1111");
test("010101010");
test("9999");
I hope it helps you. Bye
You can simply write code like
$(document).on('input', '#phNo', function() {
var mobNumber = $(this).val();
var res = mobNumber/(mobNumber/10);
if(res == 111111111) {
alert('Please enter valid phone number');
}
});
this is applicable for all numbers and you have to check the max and min length of the input ..
You can try like this,
var phone = "11111111";
var phonecount = phone.length;
var countLength = 0;
for (var i in phone)
{
if(phone.substring(0,1)==phone[i])
{
countLength = countLength + 1;
}
}
if (countLength == phonecount)
alert("Please enter valid phone number");
try this :
var checkPhone = function() {
phone_number = $('#phone').val();
res = (/^(.)\1+$/.test(phone_number) ? '1' : '0');
if(res == '1'){
return 'bad phone number';
} else {
return 'good phone number';
}
}
Test it here : JSFIDDLE

Javascript Input Numbers Only Regular Expressions

I have a RegEx validation that validates the field to be number only. However, what happens is the validation will only return true if the length of the string is more than 10 digits. But if less than 10, let's say 5, it returns false.
Here's my code:
function isNumeric(elem, helperMsg) {
var numericExpression = /^[0-9]+$/;
if (elem.value.match(numericExpression)) {
return true;
} else {
alert(helperMsg);
elem.focus();
return false;
}
}
function formValidator() {
var phone = document.getElementById('home');
if (isNumeric(phone, "Please enter a valid Australian House Phone Number")) {
console.log("Passed phone number");
if (isNumericPostal(postal, "Please enter a valid Postal Code of Australia it should be 4 digits only")) {
return true;
}
}
}
}
you are also mixing validation logic with UI logic in your isNumeric function. It's bad practice. /^\d{10,13}$/.test(yourValue) will return true/false - should be better in this case.
function isNumeric(val) {
return /^\d{10,13}$/.test(val);
}
function formValidator() {
var phone = document.getElementById('home');
if (!isNumeric(phone.value)) {
alert("Please enter a valid Australian House Phone Number");
phone.focus();
return false;
}
// do your other logic in similar manner
return true;
}
This is what you need:
/^[0-9]{0,13}$/
This will validate that the input string is between 0 to 13 digits length. So even if it 9, 10 digits it will pass.
If you have some minimum digit length as well, then change the {0,13} accordingly.
Between, http://www.regexr.com/ is a good site to create regex and test them.
Use this regex ^(\d){9,13}$ instead

Javascript phone and number field wont validate correctly submits form anyway

Update:
the script below will throw an error if I enter in a 9 digit phone number, and accept a 10 digital one ...... but it will also accept just a single digit - how can I stop this from happening.
and for the collector field I need it to accept only 11 numbers.
I'm trying to amend my validation code to validate for phone numbers, it seems like an easy enough task but I can't get it to work correctly.
The script should check to see if it is 9 digits long, spaces, dashes or no spaces are okay. If no phone is entered it should give the required error. If the field has only 8 digits for example entered it should give the invalid phone error.
Please see the code at this jsfiddle - http://jsfiddle.net/5zFqS/7/
function validate_required(field,alerttxt) {
with (field) {
if (value==null||value=="") {
alert(alerttxt);return false;
} else {return true;}
}
}
function validate_email(field,alerttxt) {
with (field) {
apos=value.indexOf("#");
dotpos=value.lastIndexOf(".");
if (apos<1||dotpos-apos<2)
{alert(alerttxt);return false;}
else {return true;}
}
}
function validate_Phone(field,alerttxt) {
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if(field.value.match(phoneno)) {
alert(alerttxt);return false;
} else {return true;}
}
function validate_collector(field,alerttxt) {
var collect = /^\d{12}$/;
if(field.value.match(collect)) {
alert(alerttxt);return false;
} else {return true;}
}
function validate_form(thisform) {
with (thisform) {
if (validate_required(firstName,"Please enter your First Name")==false)
{firstName.focus();return false;}
if (validate_required(lastName,"Please enter your Last Name")==false)
{lastName.focus();return false;}
if (validate_required(email,"Please enter your Email Address")==false)
{email.focus();return false;}
if (validate_email(email,"Please enter a valid Email Address")==false)
{email.focus();return false;}
if (validate_required(phone,"Please enter your Phone")==false)
{phone.focus();return false;}
if (validate_Phone(phone,"Please enter a valid Phone Number")==false)
{phone.focus();return false;}
if (validate_required(province,"Please select your Province")==false)
{province.focus();return false;}
if (validate_required(collector,"Please enter Collector Number")==false)
{collector.focus();return false;}
if (validate_collector(collector,"Please enter a valid Collector Number")==false)
{collector.focus();return false;}
}
}
I think I have a syntax error but I can't see it.
You need to remove the semi-colon at the end of this line:
if (field.match(/^\d{9}/));
You said that spaces etc., should be okay. In which case, you'll need to remove (or ignore) them:
var reg = /\D/g; // \D identifies non-digit characters, g means 'global'
var stripped = "888-777 66st".replace(reg,"");
// returns: 88877766
Also, use of with is not recommended
as it may be the source of confusing bugs and compatibility issues
MDN reference
Instead of
if (field.match(/^\d{9}/))
use this
if (!field.match(/\d{9}/))

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