onclick event on submit button - javascript

I'm trying to make a verification that an input text has an email format after clicking submit buttom and calling a js function. The first problem i encounter is that after some tests, i've seen that it doesnt enter the called function. After this, i think everything should be ok, but just in case in order to not post 2 almost equal questions within minutes, ill include the most important part.
Summarizing, it should check:
-The email field is not null
-The email field has an # (without taking into account order etc)
Then it should tell if it found any problem, if not leave everything unchanged
I hope i made my point, if not i can try to explain it again..
<input type="text" name="email" id="email">
<input type="submit" onclick=" proceed()"/>
<script>
proceed(){
var email= document.getElementById('email').value;
var problems;
if (email == ""){
problems = "Empty variable \n";
}
var noat = true;
for (int i=0; email.length; i++){
if (email.charAt(i) == "#"){ //Compare each character
noat=false;
break;
}
}
if (email=="" || noat=true){
problems += "No # \n"
alert(problems);
}
}
</script>

<form onsubmit="return proceed();">
<input type="text" name="email" id="email">
<input type="submit" />
</form>
<script>
function proceed() {
var email = document.getElementById('email').value;
var problems = "";
if (email == "") {
problems = "Empty variable \n";
}
var noat = false;
if (email.indexOf("#") == -1) noat = true;
// for (int i=0; i< email.length; i++){
// if (email.charAt(i) == "#"){ //Compare each character
// noat=false;
// break;
//}
if (email == "" || noat == true) {
problems += "No # \n";
alert(problems);
}
if (problems == "")
return true;
else
return false;
}
</script>

Instead of using onclick, i think you should use onsubmit and instead of comparing each character for # symbol, you should use email test regular expressions.
there are plenty of those online, just google.
sample regular expressions

Well I was about to write this myself but I happened to have found it like 4 hours ago. This will help you.
<script>
function proceed()
{
var email = document.getElementById("email").value;
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos+2 || dotpos+2 >= email.length)
{
alert("Not a valid e-mail address");
return false;
}
};
</script>
<form onsubmit="proceed();">
<input type="text" name="email" id="email" />
<input type="submit" />
</form>
Your code had a lot of typos, just take your time when writing. This is from w3schools

This question has already been marked as answered, but I feel that there a few key takeaways / learning points from the question, so i've added my input below, fwiw.
Right now the code in your question starts off with proceed() { ... }. You should change this to function proceed() { ... } to make it a proper function declaration
It's a good habit to define your variables at the top of your scope in which they are being used. As of now you have the email and problems vars declared next to each other, and that's good. However, var noat is all by itself a few lines down. Moving it up to the other declarations helps the reader of your code understand which variables are to be used in this function
On the fourth line of your function you check to see if email is an empty string. If it is, you set the problems variable. But if it's empty, we can stop where we are. You can just return problems; and be done with the function.
It's already been pointed out, but email.indexOf("#") uses the native JS method to do what you're doing in the string iterator.
for(int i=0; ...) I thought the int i =0 looked funny, so I tried typing it into the javascript console on my browser. I got an error. You can change this to for(var i = 0; ...) for the correct syntax.
Later on in the function we ask if email is empty again: if(email == ""). But we've already asked this question, and would have exited the function if it was true. We can't have an # symbol in the string if the string is empty.
This has been mentioned before but you probably want to use a regular expression to check the email.
Next we have noat = true. This will actually always evaluate to true because the result of the assignment is truthy. You're setting the value of noat to true, and javascript is like "Cool awesome looks good to me". It doesn't check if noat was originally set to true or false.
I've created and tested a jsfiddle that follows most of these recommendations. It also shows a way to make the code more concise and achieve a similar goal. Sorry if this comes off as too preachy/know-it-all, I definitely don't. This question piqued my interest and I had to respond!
window.proceed = function () {
var email = document.getElementById('email').value;
if (email == "") {
alert("Empty variable \n");
} else if (email.indexOf("#") == -1) {
alert("No # \n");
} else return true;
}
jsfiddle

Related

How to make an if statement with conditions that include "and" in javascript

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;
}

Validate that multiple Prompts have a value

I´m trying to write a simple test where I ask for name and age in separate Prompts. I´d like to validate user really adds a value in both prompts.
What´s the best way to do this validation without duplicating code?
When I click "OK" with no value, it does not ask me to add a value
function showInfo() {
//Asking for name in a prompt
var name = prompt("Name: ","");
//Checking if it is null or empty
if (name == null || ""){alert("Please enter your name");}
//Same for age
var age = prompt("Age: ","");
if (age == null || ""){alert("Please enter your age.");}
}
Also, noticed that "null" is to check the "Cancel" button, but I was able to test that if you click "Cancel", and click "Cancel" again, it does not ask for a value. How can I solve this issue?
You if condition is wrong. You should use
if (name === null || name === "") {
//you code here
}
And If you like to show prompt continusly unless user enters input below code will work:
function showInfo() {
while(1) {
//Asking for name in a prompt
var name = prompt("Name: ","");
if (name === null || name === ""){alert("Please enter your name");}
else break;
}
console.log("Name= "+name);
while(1) {
//Same for age
var age = prompt("Age: ","");
//Checking if it is null or empty
if (age === null || age === ""){alert("Please enter your age.");}
else break;
}
console.log("Age ="+age);
}
showInfo();
You could put it in a loop to ask again. Here I'm using !name to check for the
"truthyness" of name. null and an empty string are both "falsy" so, !name
will return true for them, a non-empty string is truthy, so !name will
return false for them.
function ask (msg, errMsg) {
var name;
do {
name = prompt(msg);
//Checking if it is null or empty
if (!name) {
alert(errMsg);
}
} while (!name);
return name;
}
function showInfo() {
var name,
age;
name = ask("Name:", "Please enter your name");
age = ask("Age:", "Please enter your age.");
}
showInfo();
That said, unless this is just a prototype or a small personal project only you
will use, don't do it this way! Sticking the user in a loop prompt will
frustrate most people. Most modern browsers include a "Don't show me this again"
check box. I'm not sure what would happen if the user checks it, the browser
might continue in an infinite loop and lock up or crash.
Instead it would be better to do it with a form on the page:
var elShowInfo = document.getElementById('show-info'),
elName = document.getElementById('name'),
elAge = document.getElementById('age'),
elOut = document.getElementById('output');
function showInfo (ev) {
// stop the form from submitting
ev.preventDefault();
var name = elName.value,
age = elAge.value;
if (name && age) {
// do something with name/age
elOut.textContent = name + ' is ' + age + ' years old.';
}
}
elShowInfo.addEventListener('click', showInfo, false);
<form>
<label for="name">Name:</label> <input id="name" placeholder="Please enter your name">
<label for="age">Age:</label> <input id="age" placeholder="Please enter your age">
<button id="show-info">Show info</button>
</form>
<div id="output"></div>
Every time the Show Info button is pressed it checks for the data once and then does something with it if it is there; otherwise it does nothing.
One thing to note, both prompt and the .value property of an element return strings so if you are going to use age to do some sort of calculation you will need to convert it to a number either using parseInt, age = parseInt(age, 10) or an unary +, age = +age;.
Further reading:
Truthy and Falsy: When All is Not Equal in JavaScript
Introduction to the DOM
#Arshad answer adds more clarity.
on a side note, the reason why the || didn't work is the order of evaluation.
if (age == null || "") --> evaluated as
if ((age == null) || "") --> true on Cancel, false on Ok
Hope this helps !

How to do email address validation using Javascript (without JQuery)? [duplicate]

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!!!

how validate an email that allows specific number of dots before and after # symbol

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
}
}

How do i check for a specific value in a field using javascript?

The javascript checks form values for not being empty
if(!$('nradulti').value){ok=2;}
if(!$('transport').value){ok=2;}
if(!$('plata').value){ok=2;}
if(ok==1){return true;}
else if(ok==2){
$('mesaj').innerHTML="
<span class='notarea'>Please complete all fields.</span>";
return false;
}
I need to add a new variable called spam for captcha and check that it is equal to a certain number, e.g. "what's 2+2" and the script to proceed only if the number is 4
What line do i need to add please?
Thanks!
You can accomplish this with a basic equality check. I'm not exactly sure what framework your using, but given your other calls.
if(!$('spam').value == '4'){
ok=2;
}
Add this line to your js file and declare the value for spam before this.
if($('spamInput_field_selector').value!=spam){ok=2}
Try this way
var answer = document.getElementById("answer").value;
var digit1 = parseInt(document.getElementById("digit1").innerHTML);
var digit2 = parseInt(document.getElementById("digit2").innerHTML);
var spam = digit1 + digit2;
if(answer == ""){
alert("Please add the numbers");
}else if(spam==answer){
// call script //
}

Categories

Resources