Validating a phone number in javascript [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to be able to accept any way that a user inputs their phone number. I need help to include regular expressions that can validate the length of a number, bracket, hyphens and take care of spaces.

<script>
function Myfuc() {
var x = document.forms[0]["mobile"].value;
var z = document.forms[0]["mobile1"].value;
if(x == null || x == '')
{
alert("Field canot be empty");
return false;
}
if(x[0]!=0) // Starting with zero
{
alert("Mobile number should start with Zero");
return false;
}
var y=isNaN(x); // Checking numerals in first text box
if(y == true)
{
alert("Integers only accepted");
return false;
}
var z1=isNaN(z); // Checking numerals in first text box
if(z1 == true)
{
alert("Integers only accepted");
return false;
}
}
</script>
<form onsubmit="Myfuc()">
Mobile : <input type="text" id="mobile" name="mobile" style="width:40px;" maxlength=3> -
<input type="text" name="mobile1" maxlength=7>
<input type="submit" value="Click" name="sub" >
</form>
Everything you asked is here!!!, Spent 1 hr for this and imma beginner, dont worry code works well :-)

You could use this reg expression. I'm not too good with reg expressions but this could work in your case.
0\d{2}-\d{7}
/* start match with 0
check for 2 additional digits
check for hyphen
check for 7 additional digits after hyphen
*/

I also suck at creating regex expressions; however, you can always do something like this:
var str = document.getElementById('myInput').value,
numberOnly = str.replace(/-/g, ''),
errors = [], i;
if (isNaN(numberOnly)) {
errors.push('You must use numbers!');
} else if (str.split('-')[0].length !== 3 || str.split('-')[1] !== 7 || numberOnly > 10) {
errors.push('Invalid Format!');
} else {
console.log(numberOnly + ' is ok!');
}
if (errors) {
for (i = 0; i < errors.length; i++) {
console.log(i + '. ' + errors[i]);
}
}
It's simply testing each part of the string that is submitted.
First it checks to see (after we remove the hyphen) that the submitted value is actually a number.
Second, it splits the string in half to check if the start of the string has 3 characters, and then if the end of the string has 7 characters; lastly, it tests to see if the number is too large... etc, you can even check if its too small.
If you ever figure out a decent regex, you could instead use a switch statement to catch the errors (if any).
I think one might look like, [0-9]{3}(-)[0-9]{7} or something like that lol.
-
I've been working with PHP for awhile, so I forget if "length" returns a count, or the actual byte-size of a character, e.g. "é" is 2 bytes.
EDIT:
To check if the first character of the string is "0", you can always do:
if (str.length > 0 && str.charAt(0) != 0) { console.log('error'); }

Related

characters min length in JavaScript

I am trying to make the JavaScript have a min length on the username characters. The username has to have at least 5 characters in the name. So far, I can type in the username but, still get the message we need 5 characters even if we have more or less, the only time that does not happen is when I don't type anything in. I don't quite understand why.
// version 1
let y = document.querySelector("#nick2").value; {
if(y== 0)
for(y.length=0; y.length>5; y.length++);
{
console.log("need at least 5 letters in the username ");
}
//Version 2
let y = document.querySelector("#nick2").value; {
if(y== 0)
if(y.value.length !=5){
y.value="";
input=y.value
if(input.length<5){
console.log("need at least 5 letters in the username");
}
}
What am I doing wrong?
You can check the length of your input element by calling a function within your input element's onkeyup method.
Something like this:
function check(item) {
let y = item.value.trim(); // trim() removes any extra whitespace
if(y.length < 5) {
console.log("Need at least 5 letters in username");
} else {
console.log("You've entered 5 or more characters for username");
}
}
<!-- You can pass the element as 'this' to the function -->
<input type="text" value="" onkeyup="check(this)" />
Note: If you want to allow whitespace characters (spaces) to be a valid input then remove trim().

How to write javascript in register firstname and lastname that check if inputvalue is only Characters [duplicate]

This question already has answers here:
JavaScript & regex : How do I check if the string is ASCII only?
(4 answers)
Closed 3 years ago.
I'm trying to write Javascript code for firstname and lastname validation that contains only a Hebrew characters without numbers or any symbols or any Characters from another language.
I tried to do it and it didn't work that well, The Language is Hebrew, I would like to ensure that the values contain only Hebrew characters, and it's not working that good. It must the user to put Hebrew Characters but if he adds Hebrew Characters he can add numbers or more things and I dont want it to be like that, I want it to be only Characters.
if (fname1.value == "") {
alert("אנא מלא שם פרטי");
return false;
}
if (fname1.value.length < 2) {
alert("שם פרטי חייב להיות גדול מאות אחת ");
return false;
}
if (fname1.value.length > 12) {
alert("שם פרטי חייב להיות קטן מ - 12 אותיות");
return false;
}
if (!(fname1.value >= 'א' && fname1.value <= 'ת' )){
alert("שם פרטי חייב להיות באותיות בעברית ובלי מספרים!");
return false;
}
This is what I cooked up: const onlyHebrewPattern = new RegExp(/^[\u0590-\u05FF]+$/i);
Inspired from here: https://gist.github.com/YaronMiro/248ed7b6a3113ff1fa3b1cffc5545a9f

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/

JQuery Phone Number Validation

I've am using jQuery validation plugin to validate a mobile phone number and am 2/3 of the way there.
The number must:
Not be blank - Done,
Be exactly 11 digits - Done,
Begin with '07' - HELP!!
The required rule pretty much took care of itself and and I managed to find the field length as a custom method that someone had shared on another site.
Here is the custom field length code. Could anyone please suggest what code to add where to also require it begin with '07'?
$.validator.addMethod("phone", function(phone_number, element) {
var digits = "0123456789";
var phoneNumberDelimiters = "()- ext.";
var validWorldPhoneChars = phoneNumberDelimiters + "+";
var minDigitsInIPhoneNumber = 11;
s=stripCharsInBag(phone_number,validWorldPhoneChars);
return this.optional(element) || isInteger(s) && s.length >= minDigitsInIPhoneNumber;
}, "* Your phone number must be 11 digits");
function isInteger(s)
{ var i;
for (i = 0; i < s.length; i++)
{
// Check that current character is number.
var c = s.charAt(i);
if (((c < "0") || (c > "9"))) return false;
}
// All characters are numbers.
return true;
}
function stripCharsInBag(s, bag)
{ var i;
var returnString = "";
// Search through string's characters one by one.
// If character is not in bag, append to returnString.
for (i = 0; i < s.length; i++)
{
// Check that current character isn't whitespace.
var c = s.charAt(i);
if (bag.indexOf(c) == -1) returnString += c;
}
return returnString;
}
$(document).ready(function(){
$("#form").validate();
});
The code in the question seems a very complicated way to work this out. You can check the length, the prefix and that all characters are digits with a single regex:
if (!/^07\d{9}$/.test(num)) {
// "Invalid phone number: must have exactly 11 digits and begin with "07";
}
Explanation of /^07\d{9}$/ - beginning of string followed by "07" followed by exactly 9 digits followed by end of string.
If you wanted to put it in a function:
function isValidPhoneNumber(num) {
return /^07\d{9}$/.test(num);
}
If in future you don't want to test for the prefix you can test just for numeric digits and length with:
/^\d{11}$/
You could use this function:
function checkFirstDigits(s, check){
if(s.substring(0,check.length)==check) return true;
return false;
}
s would be the string, and check would be what you are checking against (i.e. '07').
Thanks for all the answers. I've managed to come up with this using nnnnnn's regular expression. It gives the custom error message when an incorrect value is entered and has reduced 35 lines of code to 6!
$.validator.addMethod("phone", function(phone_number, element) {
return this.optional(element) || /^07\d{9}$/.test(phone_number);
}, "* Must be 11 digits and begin with 07");
$(document).ready(function(){
$("#form").validate();
});
Extra thanks to nnnnnn for the regex! :D
Use indexOf():
if (digits.indexOf('07') != 0){
// the digits string, presumably the number, didn't start with '07'
}
Reference:
indexOf().

HTML textfield whose values cannot be 0 using Javascript

I was trying to make a javascript function which will check if the user entered value inside a text field cannot be less than 9 digits & it cannot be all 0s.
This is what I made
function CheckField(field)
{
if (field.value.length <9 || field.value=="000000000")
{
alert("fail");
field.focus();
return false;
}
else
{
return true;
}
}
<input type ="text" id="number1" onBlur='return CheckField(this)'>
But this doesnt check the condition where user enters more than 9 values and all 0's. It checks only for 1 condition that is with exact 9 zeros 000000000
So, if I understand that right you want the user to be able to enter a number with more than 9 digits, but they cannot be all zeros, right?
This can be done with a regexp:
var value; // Obtain it somehow
if (/^\d{9,}$/.test(value) && !/^0+$/.test(value)) {
// ok
}
What this checks is whether the value is at lest 9 digits (it does not allow anything but digits) and that they are not all 0s.
This should check for both conditions:
function CheckField(field){
return !/0{9}/.test(field.value) && /\d{9}/.test(field.value);
}
Try something like this:
var valueEntered = field.value;
if (parseInt(valueEntered) == 0) ...
or if you wanted to check if it was a number as well:
if (!(parseInt(valueEntered) > 0))
Two options spring to mind. You can try parsing the value as a number and test for isNaN or != 0
var parsed = parseInt(field.value, 10);
if(field.value.length < 9 || !(isNaN(parsed) || parsed != 0)){
alert("fail");
... rest of code
}
Or you could use a regex
if(field.value.length < 9 || !/[^0]/.test(field.value){
alert("fail");
... rest of code
}
The first option is probably quicker.
try this:
if (field.value.length <9 || field.value.replace("0","") == "")

Categories