This question already has answers here:
How can I validate an email address in JavaScript?
(79 answers)
Closed 7 years ago.
I'm trying to do an email address validation for an input text field, however, it must only submit if the entry is not null and has the # char in it
Example 1 is the one that works, however, it excludes the need for the # char
function emailvalidation() {
var x=document.forms["input"]["email"].value;
if (x==null || x=="") {
alert("Input email address, please!");
return false
}
Example 2 which does not work, but is how I imagine it would be written
function emailvalidation() {
var x=document.forms["input"]["email"].value;
var email = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (x<>null || x<>"" && x.value.match(email)) {
alert("Input email address, please!");
return true
} else {
alert("Input email address, please!");
return false
}
}
Anyone have any ideas? Thank you though, preferably without JQuery! Thanks!
Another email validation.
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
You have a couple of logical problems in your solution.
Firstly, the condition is that x is not null and x is not an empty string and x matches the pattern.
Secondly, <> is the wrong comparator for javascript; use != or !==.
Thirdly, as pointed out by putvande x is already the element's value, so x.value.match() is probably causing you issues.
function emailvalidation() {
var x = document.forms["input"]["email"].value;
var email = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (x !== null && x !== "" && x.match(email)) {
return true;
} else {
alert("Input email address, please!");
return false;
}
}
Thank you all for this! The solution was a mixture of all of the answers! Though, here is the final solution! Needed a new reg expression and !==
Thank you all though, from a JS beginner, it is really appreciated
function emailvalidation() {
var x=document.forms["input"]["email"].value;
var email = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (x !== null && x !== "" && x.match(email)) {
return true
} else {
alert("Input email address, please!");
return false
}
}
Based on your first script and requirements, one solution without regex, and one with.
Note that a text-inputfield only returns strings.
Email-addresses must have something before the #, so we check if an # appears after the first character (using indexOf we don't require a regex). Also, if we have found the # that means the string was not empty!!
If the # is at the same position as the last # and this position is smaller then the total string-length, this gives us a true or false value, which we can instantly return.
If none of the three conditions is met, then we alert our error-message. alert returns undefined (which in itself coerces to false in javascript, but) which we force to a boolean false using double not !! and return that value.
The second example follows the same logic, but uses a regex.
function emailvalidation(){ //without regex
var s=document.forms.input.email.value
, x=s.indexOf('#');
return( x>0 && x===(x=s.lastIndexOf('#')) && x<s.length-1
) || !!alert("Input email address, please!");
}
function emailvalidation(){ //with regex
return /^[^#]+#[^#]+$/.test(document.forms.input.email.value) || !!alert("Input email address, please!");
}
<form name="input">
<input name="email" type="text" />
</form>
<button onclick="alert(emailvalidation())">test</button>
Final note, it's good that you are liberal in accepting email-addresses, since trying to do a good job in regex is long and difficult, see for example this regex: http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html
There is simply no 100% reliable way of confirming a valid email address other than sending an email to user and and waiting for a response. See also https://softwareengineering.stackexchange.com/questions/78353/how-far-should-one-take-e-mail-address-validation
If you do try to regex 'valid email-addresses' then inform your employer that you are going to cost him business/clients/cash!!!
Related
I am trying to make a password and confirmation password match, without them both being just left blank.
I would like to add in this part about the password fields not being able to be left blank, in the if statement, by saying the passwords have the same value, and these values are not blank.
The function worked fine when it was just the if statement, saying that the passwords had to match in order for the welcome alert to come up, and have found that the and symbol in javascript is && but i don't know how to use it in the context.
var check = function() {
if (document.getElementById('psw').value ==
document.getElementById('psw-repeat').value)
&&
(document.getElementById('psw').value) != ""
&&
(document.getElementById('psw-repeat').value) != "" }
else {
alert("passwords do not match")
}
}
I would expect this code to say that the passwords haven't been filled out, if they haven't, to say welcome if the password and confirmation password match, and to say the passwords do not match if they do not match.
I'm not sure what I've done wrong but would love if anyone could help.
:))
You're not closing the whole if statement with ()
Okay, best way to do conditions it like following.
why best
optimized, you don't need to get values from dom again and again for
condition checking
easy to read if condition.
If code is not readable then not the best code
So always try to break the conditions
function() {
var password = document.getElementById('psw').value;
var password_repeat = document.getElementById('psw-repeat').value;
if (password == password_repeat && password != "" && password_repeat != "")
{
// code ..........
}
else
{
alert("passwords do not match")
}
}
For better code checking and styling, use some IDEs like VSCode Atom Bracket
but personally I like the VSCode
The only real problem is out-of-place parentheses and curly braces, but this way adds a couple of improvements beyond those simple fixes.
// Select HTML elements
const psw = document.getElementById("psw");
const pswRepeat = document.getElementById("psw-repeat");
const checkBtn = document.getElementById("checkBtn");
// Listen for button clicks
checkBtn.addEventListener("click", check);
// Validate passwords
function check(){
if(pswRepeat.value === psw.value && psw.value != ""){
// We know they are the same, and psw is not empty (so neither is pswRepeat)
alert("good");
}
else{
alert("passwords do not match");
}
}
<input id="psw" />
<input id="psw-repeat" />
<button id="checkBtn">Check</button>
You forgot to close the parenthesis.
You need better indentation to detect these kinds of problems early and some separation of logic to keep the code readable.Something like this :
var check = function() {
if (isValid()) {
//Welcome here
} else {
alert("passwords do not match")
}
}
function isValid() {
var psw = document.getElementById('psw').value;
var repeatPsw = document.getElementById('psw-repeat').value;
//Logic to check for password
if (psw == repeatPsw &&
psw != "" &&
repeatPsw != ""
)
return true;
return false;
}
I have a function to validate phone number in a contact form, but i need to be able to put in "xxx xxx xxxx" for example, and not just "xxxxxxxx"
The number format should be:
xxx xxx xxxx
xxx-xxx-xxxx
xxx.xxx.xxxx
function validatePhone() {
var phone = document.getElementById("phone").value;
if (phone.length == 0) {
var w = document.getElementById("phoneError").textContent;
alert(w);
return false;
}
if (phone.length != 10) {
var r = document.getElementById("phoneError").textContent;
alert(r);
return false;
}
// THIS IS NOT WORKING
if (
!phone.match(/^[0-9]{10}$/) ||
!phone.match(/^\d{3}-\d{3}-\d{4}$/) ||
!phone.match(/^\d{3}.\d{3}.\d{4}$/)
) {
var t = document.getElementById("phoneError").textContent;
alert(t);
return false;
}
}
Two things: First, you are mixing up AND and OR:
if (
!phone.match(/^[0-9]{10}$/) ||
!phone.match(/^\d{3}-\d{3}-\d{4}$/) ||
!phone.match(/^\d{3}.\d{3}.\d{4}$/)
) {
As soon as one of the conditions fails, it will return false (which is basically always). You want this if to apply, when none of the expressions matches, e.g. when all of them are false. Therefor, you have to use && instead of ||. Not a AND not b AND not c.
Second: your 3rd regex is a bit off: . means "any character", so this regex would also match "123x123y1234". You need to escape the dot with a backslash: /^\d{3}\.\d{3}\.\d{4}$/
Also, you can improve this code significantly. You have 5 conditions, which could all be handled in one (if you want to allow the input of "123.123 234", otherwise you will have to do it using 3 regex). And for just checking if a regex matches a string, you maybe should use test(), because it is just slightly faster (it won't matter in your case, but just out of principle).
You can reduce your code to:
if (/^\d{3}[\s-.]\d{3}[\s-.]\d{4}$/.test(document.getElementById("phone").value) === false) {
alert (document.getElementById("phoneError").textContent);
return false;
}
i have poor eng, Sorry for that.
i'll do my best for my situation.
i've tried to make SignUpForm using regular expression
The issue is that when i handle if statement using the regular expression
result is true at first, but after that, become false. i guess
below is my code(javascript)
$(document).ready(function () {
var idCheck = /^[a-z]+[a-z0-9]{5,19}$/g; // more than 6 words
var pwCheck = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/; // more than 8 words including at least one number
var emCheck = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/; // valid email check
var signupConfirm = $('#signupConfirm'),
id = $('#id'),
pw = $('#pw'),
repw = $('#repw'),
email =$('#email');
signupConfirm.click(function () {
if(id.val() === '' || pw.val() === '' || email.val() === ''){
$('#signupForm').html('Fill the all blanks');
return false;
} else {
if (idCheck.test(id.val()) !== true) {
$('#signupForm').html('ID has to be more than 6 words');
id.focus();
return false;
} else if (pwCheck.test(pw.val()) !== true) {
$('#signupForm').html('The passwords has to be more than 8 words including at least one number');
pw.focus();
return false;
} else if (repw !== pw) {
$('#signupForm').html('The passwords are not the same.');
pw.empty();
repw.empty();
pw.focus();
return false;
}
if (emCheck.test(email.val()) !== true) {
$('#signupForm').html('Fill a valid email');
email.focus();
return false;
}
}
})
});
after id fill with 6 words in id input, focus has been moved to the password input because the condition is met.
but after i click register button again, focus move back ID input even though ID input fill with 6 words
i've already change regular expression several times. but still like this.
are there Any tips i can solve this issue?
I hope someone could help me.
Thank you. Have a great day
Do not use the global flag on your regexes. Your code should be:
var idCheck = /^[a-z]+[a-z0-9]{5,19}$/;
When you match with the /g flag, your regex will save the state between calls, hence all subsequent matches will also include the previous inputs.
use
var idCheck = /^[a-z]+[a-z0-9]{5,19}$/
removing the g flag
and modify the line
else if (repw.val() !== pw.val()) {
I have a problem in email validation i have two email formats based on those email formats only i need to check the validations If by mistakenly user enter out of these two emails raise alert message below my code is not working properly how can i do this
var atpos = email.indexOf("#ho.XXX");
var atpos1 = email.indexOf("#YYYY");
var dotpos = email.lastIndexOf(".com");
if (atpos<1 && atpos1<1 || dotpos<atpos+2 ||dotpos<atpos1+2 || dotpos+2>=email.length){
alert("Email Should be in ##ho.XXX.com or #YYYY.com");
document.getElementById("txtEmail").focus();
return false;
}
when i am taking the above if-condition it accepts both the email id's. I need to accept only one for at a time. If the user enter both at a time display error message like enter only one email id and when i enter some text after .com like .comyu it accepts without showing any error how to validate .com show error in this case
If you just need to check if your email ends in '#ho.XXX.com' or '#YYYY.com' and these are the fixed domains you wish to look for, then you could simply start with below:
function checkval(v) {
if (!v.endsWith("#ho.XXX.com") && !v.endsWith("#YYYY.com"))
alert("value is bad : " + v);
else
alert("value is good : " + v);
};
checkval("test#ho.XXX.com");
checkval("sasdf#YYYY.com");
checkval("xxxx#ho.XX.com");
checkval("sasdf#YYY.com");
--- Snippet Edited to use endsWith. Documentation here
The endsWith() method determines whether a string ends with the characters of a specified string, returning true or false as appropriate.
Tip : You could by all means attempt with Regular expressions and make your code much more scalable, but it depends on your use case.
--- EDIT with DeMorgan's Law ---
Not (a or b) = (not a) and (not b)
!(a || b ) = !a && !b
You should use the regular expressions. Example
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);
}
Then you can modify the pattern as you want.
I updated the function validateEmail as your requirement (Just acept email (#ho.XXX.com or #YYYY.com). So you can try and modify.
function validateEmail(email) {
var re = /^[a-z0-9._%+-]+#(ho.XXX.com|YYYY.com)$/;
return re.test(email);
}
var val_em=document.add_indus_detail_form.txt_email.value;
var atpos=val_em.indexOf("#");
var dotpos=val_em.lastIndexOf(".");
if(val_em!='')
{
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=val_em.length)
{
alert("Not a valid e-mail address");
return false;
}
}
i use this condition to check the email validation that user enters in the textbox how i can validate it like it allows 3 or 4 or any specific numbers of dot allow (ex abc.abc.abc.abc#abc.abc.com) before and after the # but do not allow that dots together (ex: abc#abc...com). also do not allow the spaces in email how it will be have you any idea for this type of validation..
I would suggest a regex for this
function validateEmail(email){
var emailReg = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
var valid = emailReg.test(email);
if(!valid) {
return false;
} else {
return true;
}
}
call the function validateEmail whenever you need....
Validations in JavaScript are useless. The user can turn off JS or maybe you encounter a browser who cant even understand JS. This makes your page vulnerable to attacks. So NEVER use JS for validating user inputs.
What you want is RegEx or many if-conditions together with string-functions. My approach: Use a For-Loop, go through the string one by one, check the current character and the one after it. Like this:
for($i = 0; $i < strlen($string); $i++) {
if(substr($string, 0, 1) == '.' {
//do something
}
}