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))
Related
i want to validate a password field with the following conditions:
One uppercase character
One lowercase character
One number
One special character
Eight characters minimum
If the password input is correct i want to make the pass field green if not it should be red.
I tried with this code but doesnt work:
let password = document.querySelectorAll(".control-group")[3];
password.addEventListener("focusout", () => {
let inp = password.value;
if (
inp.match(/[a-z]/g) &&
inp.match(/[A-Z]/g) &&
inp.match(/[0-9]/g) &&
inp.match(/[^a-zA-Z\d]/g) &&
inp.length >= 8
) {
password.style.backgroundColor = "green";
} else {
password.style.backgroundColor = "red";
}
});
The code you provided is not working due to the fact that
inp.match(/[a-z]/g) && inp.match(/[^a-zA-Z\d]/g)
is just "false". You are telling there "if it contains alphabetic characters as well as it doesn't contains any", which is some sort of
let i = 0;
if (i == 1) {...}
As I said on one of the comments of your question, just search for another solution, like the one that #harsh-saini said.
Output of match() is not true or false, but the match thing like str or int or if it wrong it will show null. So in your case better use "if your case (if input.match() != null) as true". There is the example !
var input = "GoodMorning Sir"
if (input.match(/[0-9]/g) != null){
console.log("there are number here")
} else if (input.match(/[A-Z]/g) != null){
console.log("there are uppercase here")
}
//this is your if else code, try to console.log your condition
//as you can see it wont giving output true or false
console.log(input.match(/[A-Z]/g)) // ["G", "M" , "S"]
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)) {
}
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.
Hi guys i got a problem here, how i can validate a password box that must contain at least one numeric character. i'm not allowed using regular expression / regex. i have tried searching over the web, but the solution is always end with regex.
here's my code that i try
function validateIn()
{
var pass=document.getElementById('password').value;
for(var i=0;i<pass.length;i++)
{
if(isNaN(pass.charAt(i))==false)
{
return true;
break;
}
else
{
return false;
}
}
}
i have tried that way but i fail, can u help me guys? thanks before
One possible approach:
function validateIn() {
var pass = document.getElementById('password').value,
p = pass.length,
ch = '';
while (p--) {
ch = pass.charAt(p);
if (ch >= '0' && ch <= '9') {
return true; // we have found a digit here
}
}
return false; // the loop is done, yet we didn't find any digit
}
The point is, you don't have to return immediately after you have found a normal character (as you're basically looking for a single digit) - you just have to move on with your checking.
Note that I have gone without isNaN, as it's a bit inefficient: the only thing required is a range check.
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})?)*$">