Mobile number field accepts invalid number too - javascript

Here is a validation code that I use to validate mobile number. If I enter a mobile number with alphabets or any invalid number, it accepts that too. Can someone suggest what is wrong in this?
Thanks
var g=document.getElementById('mobile').value;
if (g.length == 0 )
{
alert( "Please Enter Mobile Number." );
formn.mobile.focus();
return false;
}
if(g.length>0)
{
if((g.length<10)||(g.length>10))
{
alert( "Mobile number should be 10 digits");
document.getElementById('mobile').focus();
return false;
}
else
{
var h3=/^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$/;
if(g.match(h3)!=null)
{
alert( "Please Enter Valid Mobile Number");
document.getElementById('mobile').focus();
return false;
}
}
}
EDIT : I was thinking of removing the condition of 10 digits and allow user to input the mobile numbers as per their choice and their own way and then replace/reformat using a regex so that only 10 digits mobile number goes into the database. During google search I found somewhere on stackoverflow that ^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$ works well for reformating in following scenarios. Appreciate if someone can help me reformat it and show the reformatted digits when the user goes into the next textbox (losing focus)
9883443344
09883443344
919883443344
0919883443344
+919883443344
+91-9883443344
0091-9883443344
+91 -9883443344
+91- 9883443344
+91 - 9883443344
0091 - 9883443344

Use Below code :-
var g=document.getElementById('mobile').value;
if (g.length == 0 )
{
alert( "Please Enter Mobile Number." );
formn.mobile.focus();
return false;
}
if(g.length>0)
{
if((g.length<10)||(g.length>10))
{
alert( "Mobile number should be 10 digits");
document.getElementById('mobile').focus();
return false;
}
else
{
var h3=/^[1-9]{1}[0-9]{9}$/;
if(h3.test(document.getElementById('mobile').value) == false)
{
alert( "Please Enter Valid Mobile Number");
document.getElementById('mobile').focus();
return false;
}
}
}
Updated your regex code.

why not just use [0-9] as a regex, basicly if it is not in 0-9 it is invalid, maybe you want + for international calls that is 00 infront of phone number..
Please check out these testers also if you have not already:
http://www.regexpal.com/
https://regex101.com/
http://www.regexr.com/
var re = /[0-9+]/g;
var str = '0700';
var m;
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
If it is not in found with /[0-9+]/g it is not legal

This regular expression fits for all use-cases you mentioned and strictly rejects other patterns.
((00)|\+|0)?((91)|0)?\s{0,2}-?\s{0,2}(\d{10})

Related

/ operator (or some other part of the code) doesn't seem to work

I wrote a simple code in javascript that was supposed to validate the length of a phone number inputed in an html form (check if it consists of 10 digits- as it is in my country).
So here's the function:
function check_tel(){
var tel=document.LpData.phone.value;
var i=0;
for(;i<10;i++){
tel/=10;
if(tel==0){
alert("unvaild phone number- too short");
return false;
}
}
if(tel>0){
alert("unvaild phone number- too long");
return false;
}
return true;
}
But it always outputs that the number is too long (i>10).
I already checked the value of "tel" variable before it enters the loop and everything is right.
I also tried it with a "while" instead of "for" loop.
So I concluded it's because of the "/" operator which doesn't work (although I still don't understand how it's possible) or it has something to do with the type of tel...
So what is the problem and how to fix it?
Thanks in advance!
Every input value is always a string. Using the divide operator on a string is not what you wanted. So you may convert the phonenumber to an int:
function check_tel(){
var tel=parseInt(document.LpData.phone.value,10)||0;
for(var i=0;i<10;i++){
tel/=10;
if(tel<1){
alert("unvaild phone number- too short");
return false;
}
}
tel/=10;
if(tel>1){
alert("unvaild phone number- too long");
return false;
}
return true;
}
also note that 123456789/10000000 is not 0...
and by the way, it is much easier to simply check for tel.length...
The best practice to do these things is to use a Regular Expression(Regex).
/^\d{10}$/ is a JS regex to check if the number is a 10 digit number.
function check_tel()
{
var tel = document.LpData.phone.value;
var teleRegex =/^\d{10}$/;
if(!teleRegex.test(tel)){
alert("invalid phone number")
}
else{
//do your thing
}
}
Possible work-around is
function check_tel()
{
var tel=document.LpData.phone.value;
if(tell.length == 0 || tell.length > 10){
alert("invalid phone number");
return false;
}
return true;
}
Try var tel = parseInt(document.LpData.phone.value); instead of var tel = document.LpData.phone.value;

validate an australian phone number

I have been attempting to validate an australian phone number using javascript however it has been accepting everything. It needs to be 10 numbers long beginning with 0 accepting spaces:
02 4345 2334
and together
0243452334.
I think the regex might be wrong or the code itself
function PhoneNumberVal(form){
var phoneFormat= /^0[0-8]{2})\)?[ ]?([0-9]{4})[ ]?([0-9]{4})$/;
var phoneLength = document.getElementById('phone').value.length;
if(phoneFormat.test(phoneLength)) {
return true;
} else {
alert("Not a valid phone number");
return false;
}
}
Your regex is wrong. ^0[0-8]{2})\)?[ ]?([0-9]{4})[ ]?([0-9]{4})$ you failed to put the opening parenthesis and you need to change [0-8]{2} to [0-8], since your input contains exactly 10 digits.
^(?:\(0[0-8]\)|0[0-8])[ ]?[0-9]{4}[ ]?[0-9]{4}$
DEMO
Use this Regex,
/^\D*0(\D*\d){9}\D*$/
Demo
Regex? Ha! Now you have two problems.
UPDATE: This version should be final.
Just do this:
function IsAustralianTelephoneNumberValid(a_telephone)
{
a_telephone = a_telephone.replace(/\s/g, ''); // remove all spaces
// if is empty OR first char is NOT 0
if((a_telephone=='')||(a_telephone.charAt(0)!='0'))
{
alert("Not a valid phone number");
return false;
}
// lets save the length of that string before we remove digits
length_with_digits = a_telephone.length;
// now string has its digits removed
a_telephone = a_telephone.replace(/0|1|2|3|4|5|6|7|8|9/g,'');
// if is nothing, then there was no other characters in string
// except digits and spaces AND ALSO if the difference of length before the digits
// removal and now is 10 then we can be sure we had 10 digits and nothing else,
// so its valid. Any other case is not valid.
if((a_telephone=='')&&(length_with_digits-a_telephone.length==10))
{
alert('ok');
return true;
}
else
{
alert("Not a valid phone number");
return false;
}
}
http://jsfiddle.net/L7vzL4jm/10/

Regular Expression to check a value must allow only two digits after decimal point?

I'm working on asp.net web application project.
I'm taking input from a TextBox.
TextBox must allow a numeric value which is greater than zero and must have two digits after decimal.
I'm validating textbox in javascript.
Please suggest me regular expression to achieve it.
In my code its failing in some cases.
var conversionRate = $.trim($("#ConversionTextBoxID").val());
if (conversionRate == "") {
// alert("Please Enter Conversion Rate.");
modalWin.ShowMessage('Please Enter Conversion Rate.', 200, 400, 'Message');
return false;
}
else if (Number(conversionRate) == 0) {
//alert("Please enter value greater than zero for Conversion Rate.");
modalWin.ShowMessage('Please enter value greater than zero for Conversion Rate.', 200, 400, 'Message');
return false;
}
else if (Number(conversionRate) == 0.00) {
// alert("Please enter value greater than zero for Conversion Rate.");
modalWin.ShowMessage('Please enter value greater than zero for Conversion Rate.', 200, 400, 'Message');
return false;
}
if (Number(document.getElementById('ConversionTextBoxID').value) > 999.99) {
modalWin.ShowMessage('Please Check Current Conversion Rate.It Can Not Exceed 999.99.', 200, 400, 'Message');
// alert("Please Check Current Conversion Rate.It Can Not Exceed 999.99.");
return false;
}
if (Number(document.getElementById('ConversionTextBoxID').value) < 0) {
// alert("Please Check Current Conversion Rate.It Can Not be less than Zero.");
modalWin.ShowMessage('Please Check Current Conversion Rate.It Can Not be less than Zero.', 200, 400, 'Message');
return false;
}
if (document.getElementById('ConversionTextBoxID').value.indexOf(".") == -1) {
//alert("Please enter decimal value for Currency Conversion Rate.");
modalWin.ShowMessage('Please enter decimal value for Currency Conversion Rate.', 200, 400, 'Message');
return false;
}
if (String(Number(document.getElementById('ConversionTextBoxID').value)).indexOf(".") < (String(Number(document.getElementById('ConversionTextBoxID').value)).length - 3)) {
// alert("Conversion Rate can have only two digits after Decimal.");
modalWin.ShowMessage('Conversion Rate must have only two digits after Decimal.', 200, 400, 'Message');
return false;
}
It fails in some cases.
example:
12.0 it fails(I don't want to allow this).
12.1 it fails.
in other cases its working fine.
So if there is any simple way or regular expression, it will be very helpful.
Try this (I have assumed 12.00 is valid but 12, 12.0 are not):
function validate(s) {
var n = Number(s)
if (n > 0 && n <= 999.99) {
if (!s.match(/\d{1,3}\.\d{2}/)) {
return console.log("invalid")
}
} else {
return console.log("invalid")
}
console.log("valid")
}
Try this but this will allow zero u might have to add a condition for that check
/[0-9]+\.[0-9]{2}([^0-9]|$)/
If you are looking for, (15,15.0 is invalid) but (15.00) is valid.
Try it,
^([1-9]{1,2})(\.[0-9]{2})$
else if you are looking for 15,15.00 valid but 15.0 invalid
Then try it..
^([1-9]{1,2}){1}(\.[0-9]{2})?$
Working Fiddle Link..
http://regex101.com/r/mN1iT5/4

How to check if String starts with number in javascript

I am trying to figure out if a user has entered an email id or a phone number. Therefore i would like to check if the string starts with +1 or a number to determine if it is a phone number . If it is not either i come to the conclusion it is an email or i could check if it starts with a alphabet to be sure. How do i check this . I am horrible with regex if that is the soln .
You can do this with RegEx, but a simple if statement will work as well, and will likely be more readable. If an # character is not present in the string and the first character is a number, it is reasonable to assume it's a phone number. Otherwise, it's likely an email address, assuming an # is present. Otherwise, it's likely invalid input. The if statement would look like this:
if(yourString.indexOf("#") < 0 && !isNaN(+yourString.charAt(0) || yourString.charAt(0) === "+")) {
// phone number
} else if(yourString.indexOf("#") > 0) {
// email address
} else {
// invalid input
}
if (!isNaN(parseInt(yourstrung[0], 10))) {
// Is a number
}
Just do the following:
if ( !isNaN(parseInt(inputString)) ) {
//this starts with either a number, or "+1"
}
Might I suggest a slightly different approach using the regex email validation found here?
if(validateEmail(input_str)) {
// is an email
} else if(!isNaN(parseInt(input_str))) {
// not an email and contains a number
} else {
// is not an email and isn't a number
}
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
This way you can check a little more thoroughly on what the input actually is, rather than just guessing it's one or the other.

javascript regular expressions for password

i have to create a regular expression for password in java script with the following criteria
1. The password should contain atleast one alphabet either upper case or lower case
2. It should contain atleast one number
3. It should contain atlease one special character(`,~,!,#,#,$,%,^,&,*,_,+,=)
var userpw = "musSTER123#";
var invalid = false;
if(!userpw.match(/\d/) || !userpw.match(/[a-zA-Z]/) || !userpw.match(/['~!##$%&*_+=]/))
invalid = true;
alert('pw is valid?' + !invalid);
Use these regexps:
[a-zA-Z] for at least one letter
[0-9] for at least one digit
['~!##$%&*_+=^] for at least one of the special characters you mentioned OR
[^a-zA-Z0-9] for at least one character that is neither a letter nor a digit
But even better would be to support single-sign-on with OpenID, SSL client certificates or a way to make the browser store a long password in its password storage without even showing it to the user (maybe some password input that's prefilled by javascript and hidden with CSS).
Don't require strong passwords. They are fool's gold. Yes, a strong password is better than a weak one, all other things being equal. But all other things are rarely equal. A strong password is more likely than a weak one to end up on a post-it note stuck to the user's monitor.
A far better defence is a good lock-out policy. A system that does nothing more than disallow passwords containing dictionary words, but locks IP addresses out for one hour after three failed login attempts will still be over 99% secure after one year of constant battering by brute force. Also, you can make it much stronger by increasing the lock-out period for continued failed attempts.
These posts were helpfull here is a bit of code some of you may want to use at some point. This forces the user to input an Uppercase, Lowercase, Special character, and minimum of 8 characters in length. It also breaks it up and lets them know what exactly it is they are doing wrong.
<script type="text/javascript" language="javascript">
function validate() {
if (document.aspnetForm.PasswordValue.value == '') {
alert('Current Password is a required field!');
document.aspnetForm.PasswordValue.focus()
return false;
}
if (document.aspnetForm.NewPasswordValue.value == '') {
alert('New Password is a required field!');
document.aspnetForm.NewPasswordValue.focus()
return false;
}
if (document.aspnetForm.NewPasswordValue.value.match(/\d/) == null) {
alert('Your new password must have a number!');
document.aspnetForm.NewPasswordValue.focus()
return false;
}
if (document.aspnetForm.NewPasswordValue.value.match(/[a-z]/) == null) {
alert('Your new password must have an Upper and lower case letter!');
document.aspnetForm.NewPasswordValue.focus()
return false;
}
if (document.aspnetForm.NewPasswordValue.value.match(/[A-Z]/) == null) {
alert('Your new password must have an Upper and lower case letter!');
document.aspnetForm.NewPasswordValue.focus()
return false;
}
if (document.aspnetForm.NewPasswordValue.value.match(/['~!##$%&*_+=]/) == null) {
alert('Your new password must have a special character i.e.(!##$%&*)');
document.aspnetForm.NewPasswordValue.focus()
return false;
}
if (document.aspnetForm.NewPasswordValue.value.length < 8) {
alert('Your new password must have a minimum of 8 characters!');
document.aspnetForm.NewPasswordValue.focus()
return false;
}
if (document.aspnetForm.NewConfirmPassword.value == '') {
alert('Confirm New Password is a required field!');
document.aspnetForm.NewConfirmPassword.focus()
return false;
}
if (document.aspnetForm.NewPasswordValue.value != document.aspnetForm.NewConfirmPassword.value)
{
alert('New password and Confirm New Password do not match!');
document.aspnetForm.NewConfirmPassword.focus()
return false;
}
if (document.aspnetForm.PasswordValue.value == document.aspnetForm.NewPasswordValue.value) {
alert('Your current password and new password are the same!');
document.aspnetForm.NewPasswordValue.focus()
return false;
}
}
</script>

Categories