How to check if String starts with number in javascript - 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.

Related

How to validate IP Address to make sure user enter 3 digits in four parts?

I was able to create a script to validate IP address correctly like this,
var ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
if(g_form.getValue('src_nw_ip_hdcc').match(ipformat)){
return true;
}else{
alert("You have entered an invalid Network IP Address!");
return false;
}
The results was great but until then they made a unusual request that they require me to validate user enter 3 digits and not allow enter 1 or 2 digits like for example,
user can't enter 115.42.150.37, instead must enter 115.042.150.037. How can I add verify to ensure they enter 3 digits?
You can do it by removing alls "?" in the regex.
This way your regex requires 3 digits every time and accepts things like 192.168.001.001
^(25[0-5]|2[0-4][0-9]|[01][0-9][0-9])\.(25[0-5]|2[0-4][0-9]|[01][0-9][0-9])\.(25[0-5]|2[0-4][0-9]|[01][0-9][0-9])\.(25[0-5]|2[0-4][0-9]|[01][0-9][0-9])$
In your code it has [01]?[0-9][0-9]. It says it can have a leading 0 or 1 or not followed by two numbers. Simple fix is to remove the ? where it makes the 0 and 1 optional
/^(25[0-5]|2[0-4][0-9]|[01][0-9][0-9])\.(25[0-5]|2[0-4][0-9]|[01][0-9][0-9])\.(25[0-5]|2[0-4][0-9]|[01][0-9][0-9])\.(25[0-5]|2[0-4][0-9]|[01][0-9][0-9])$/
I think this regex will do the job. Hope this helps.
const regex = /^(((25[0-5])|(2[0-4][0-9])|([01][0-9]{2}))\.){3}((25[0-5])|(2[0-4][0-9])|([01][0-9]{2}))$/g;
console.log('Should match');
console.log('255.255.255.255'.match(regex));
console.log('012.000.255.001'.match(regex));
console.log('000.000.000.000'.match(regex));
console.log('Should not match');
console.log('255.255.255.'.match(regex));
console.log('255.255.255.-1'.match(regex));
console.log('.255.255.'.match(regex));
console.log('255.275.255.'.match(regex));
console.log('255.275.255.1'.match(regex));
console.log('25.5.55.1'.match(regex));
You can use split() and every() in conjunction to get that validation work:
function checkIp(ip) {
var isCorrect = ip.split('.').every(addr => addr.length === 3);
if (isCorrect) {
return 'Ip address is correct';
}
return 'Ip address is incorrect';
}
var ip = '115.042.150.037';
console.log(checkIp(ip));
ip = '11.042.150.037';
console.log(checkIp(ip));

Javascript RegExp multiple rules

Currently I am trying to write a code for validation for my site contact info, and I am stuck for 3 hours now on a probably some small problem, but I just can't figure it out.
The problem I have appears in second IF element inside else element, I want to make regex search for numbers [/d] and whitespace [/s] in selected string, but my code always sees only one rule, and ignores the other one.
I guess the mistake is that i didn't write it well, but I can't figure out how. Please give me some pointers where am I making mistake.
if (sFirstname == null || sFirstname == "") {
alert("First name must be filled out");
return false;
}
else {
if (/\d/, /\s/i.test(sFirstname)){
alert("Only Letters can be used in First name")
return false;
}
else {
alert("true")
return true;
}
}
There are many small thing I would like to change:
!sFisrtname will go true as long as sFirstname is not falsy ("", 0,
null, undefined, ...)
Use else if ... instead of else { if ... }.
The statement /\d/, /\s/i.test(...) will be evaluated to:
/\d/,
/\s/i.test(...)
Same as:
var a = /\d/;
var b = /\s/i;
a, (b.test(...))
What you want is properly /[\d\s]/.test(...) which will go true if there is a
digit or a space in sFirstname. You might consider changing the logic op-in
instead of op-out, eg: /[^a-zA-Z]/.test(...). Allow only a-z and A-Z
I made the function return the error instead of alerting it:
console.log(checkFirstName('John')); // "" (no error)
console.log(checkFirstName('John 42')); // "Only a-z can be used in first name"
This can also be used in an if statement:
var error = checkFirstName('John');
if (error) {
alert(error);
}
else {
alert('Everything is fine!');
}
And the function:
function checkFirstName(sFirstname) {
if (!sFirstname) {
return 'First name must be filled out';
}
else if (/[\d\s]/.test(sFirstname)) {
return 'Only letters can be used in first name';
}
else {
return "";
}
}
Please test it like this in your "if" condition, inside else. This regular expression will test only for alphabetic, not for numeric or blank space.
var regx = /[^a-zA-Z]+/;
regx.test(firstname);
change your IF statement like below
if (/\d|\s/i.test(sFirstname))

Netbeans Field Validation (Alphabetical\Numerical\Lenght)

First i'd like to mention that i've been researching about this for few days and although i found some answers that should have been helpful i was unable to use them correctly due to the fact that i am not that much into programming yet and got no experience and might be missing something.
Straight to the point, i have a registration form and i need field validation i already have the one that validate email and empty fields for others but i need to add to the code a part that would reject numerical entries in name fields and alphabetical characters for ID field and to limit the length of a field.
Let's start with the Name field which i want to allow alphabetical characters only here is my current code:
{
var fn=document.forms["myForm"]["FirstName"].value;
if (fn==null || fn=="")
{
alert("First name must be filled out");
return false;
}
And that's my ID field which i want to limit to numerical entries only
var id=document.forms["myForm"]["ID"].value;
if (id==null || id=="")
{
alert("ID must be filled out");
return false;
}
I want to a couple of lines that would limit entries to a specific number of characters as well, how do i do that?
To check for a string length in Javascript you can use the .length method:
// this checks if the fn length is more than 10
if (fn.length > 10) {
}
To check if a value is numeric you can parse it and make sure that returns a valid output:
// This checks if id is not a valid integer
if (isNaN(parseInt(id)) {
}
To check if a value is alphabetical only you have to make sure the characters in it fall within the alphabets range, you can add a function that checks for that:
// This loops on every character of value and makes sure it is part of the letters string
function isAlphabetical (value) {
var letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
for (i = 0; i < value.length; i++) {
if (letters.indexOf(value.charAt(i), 0) == -1) {
return false;
}
return true;
}
}
And then call it from your if statement:
// This checks if fn is not alphabetical
if (!isAlphabetical(fn)) {
}

Multiple zip codes separated by a comma

I want to filter multiple zip codes in an input, there should be at least 2 zip SEPARATED by a COMA, I am trying to validate them in javascript with the following code but it's now filtering, the submit send the form to the next page without error, anyone can help?
<script>
function validateMULTIZIP() {
if(!/\d{11,}/.test(document.zipad.textfield.value) && document.getElementById('single').checked==false))
{
alert( "There should be a least two Zip codes separated by a coma." );
document.zipad.textfield.focus() ;
return false;
}
return true;
}
</script>
This will check for two 5-digit numbers separated by a comma
^\d{5},\d{5}$
But, you said at least two, so that means it needs to be a little more flexible to accommodate more. If the user enters 12345,12345,12345 it needs to be valid.
^\d{5}(?:,\d{5})+$
What if the user adds a space after the comma? Such as 12345, 12345. This is perfectly valid, so let's make sure our validator allows that.
^\d{5}(?:,\s*\d{5})+$
Oh, and zip codes can have an optional -1234 ending on them, too (known as ZIP+4. Maybe you want something like this
^\d{5}(?:-\d{4})?(?:,\s*\d{5}(?:-\d{4})?)+$
Now strings like this would be valid
12345
12345, 12345,12345
12345, 12345-9999, 12345
As a bonus, let's say 12345, 12345 is invalid because it has the same zip code twice. Here's how we'd fix that
(?:(\d{5}),?)(?!.*\1)
And here's the ZIP+4 version
(?:(\d{5}(?:-\d{4})?),?)(?!.*\1(?!-))
This one has a little added complexity because of possibility of (e.g.,) 12345, 12345-9999. This is valid but because 12345 can appear more than once, it makes sure that a 5-digit zip code can't be invalidated by a unique 9-digit zip code.
Note these duplicate-checking regexps do not enforce the minimum of two unique zip codes. If you want to check for duplicates you'd need to combine the two.
var valid5DigitZipCodes = function(str) {
if (! /^\d{5}(?:,\s*\d{5})+$/.test(str)) {
alert("You need at least 2 zip codes");
return false;
}
else if (! /(?:(\d{5}),?)(?!.*\1)/.test(str)) {
alert("You entered a duplicate zip code");
return false;
}
return true;
};
And here's the ZIP+4 variant if you want to support that
var valid9DigitZipCodes = function(str) {
if (! /^\d{5}(?:-\d{4})?(?:,\s*\d{5}(?:-\d{4})?)+$/.test(str)) {
alert("You need at least 2 zip codes");
return false;
}
else if (! /(?:(\d{5}(?:-\d{4})?),?)(?!.*\1(?!-)).test(str) {
alert("You entered a duplicate zip code");
return false;
}
return true;
};
Assuming (from your code) that ZIP code contains five digits and no other characters, you could use:
/\d{5},\d{5}/.test(document.zipad.textfield.value)
You regex: \d{11,} means "any digit, eleven times or more", that's why it's broken.
Another Solution without using regex would be splitting zip Codes by comma then check for the size of the resulting array.
Sample code:
<input type="text" id="in"></input>
<button onclick="validate()">Click</button>
JS
function validate() {
var inp = document.getElementById("in");
var content = inp.value;
var correct = validateZipString(content);
if (correct) {
alert("ok");
} else {
alert("not ok");
}
}
function validateZipString(zipString) {
var zipCodes = zipString.split(',');
if (zipCodes.length < 2) return false;
for (var i = 0; i < zipCodes.length; i++) {
//validate each zipCode if required
}
return true;
}
here is a working jsfiddle http://jsfiddle.net/VcNd9/3/
For anyone else interested in the variant that also matches 1 zip or more rather than two or more. Simply change the + quantifier for * at the end of the expression.
From:
^\d{5}(?:-\d{4})?(?:,\s*\d{5}(?:-\d{4})?)+$
To:
^\d{5}(?:-\d{4})?(?:,\s*\d{5}(?:-\d{4})?)*$
For example:
<input type="text" inputmode="numeric" pattern="^\d{5}(?:-\d{4})?(?:,\s*\d{5}(?:-\d{4})?)*$">

Novice Javascript query about bad input

I am making a simple tip calculator to help myself learn Javascript. The problem I can't solve is how to compensate for "bad input".
In the code below if the user prefaces the numeric input amount with a dollar sign $, the result is NAN.
function tipAmount(){
var dinner=prompt("How much was dinner?");
result = dinner*.10;
alert("Your tip is " +"$"+result );
}
How do I fix that.
You can try to parse out the numeric value with a regular expression:
var match = dinner.match(/\d+\.?\d*/); // parse with a regular expression
if(!match) { // not able to parse
alert("wrong");
}
var price = +match[0]; // convert to a number
result = price * .10;
The regular expression /\d+\.?\d*/ means: one or more digits, and possibly a dot with other digits following. This means that if e.g. dinner is "$1.23", price will be the number 1.23. The same goes for "$ 1.23" or "1.23 dollar" etc - the number will be parsed out with the pattern defined by the regular expression.
The simplest way would be to parse the input into a float, and see if NaN is returned.
if (isNaN(parseFloat(dinner)))
alert("Bad Input")
Just note that 45.2WWW will return 45.2, and so the above will pass.
If you want to make sure what the user typed in is exactly a number, you could do something like this:
var str = '3.445';
var num = parseFloat(str);
if (isNaN(num) || str.length !== num.toString().length)
alert("Bad Input");
try to parse the input as float or integer depending on your needs:
var dinner = parseFloat(prompt("How much was dinner?"));
or
var dinner = parseInt(prompt("How much was dinner?"));
this functions return 0 whether they unable to parse the input as number
Given your approach of using alerts, the following will work:
function tipAmount() {
var dinner=prompt("How much was dinner?");
//convert "dinner" to a number, stripping out any non numeric data
dinner = Number(dinner.replace(/[^0-9\.]+/g,""));
//any unknown data will convert to 0
if(dinner <= 0) {
alert("Please enter a valid amount");
return false;
}
var result = dinner*.10;
alert("Your tip is " +"$"+result );
return true;
}
Please tip more!
Just check if the value is numeric - Javascript's isNaN:
if (isNaN(dinner)) {
alert('Bad number, bub.');
return;
}
Or, if you want to allow users to type in both - just number or an amount with $ at the beginning, you can check for first char:
if( dinner.charAt(0) == '$' )
{
dinner = dinner.substring(1);
}
This way, whenever user types $, your app will just remove it. If they type a normal number it will calculate the tip for you...

Categories