How to use onClick ONLY if email input field is valid? - javascript

Here's code:
<input id="subscribe-email" type="email" placeholder="john.doe#example.com" />
<button type="submit" id="subscribe-submit" onClick="javascript:omgemailgone();" />
How do I check and run JS function only if email is valid (validation by user-agent, no additional validations)?
UPDATE.
New browsers can validate input=email by themselves, also there are pseudo classes :valid and :invalid. I need to run function only if browser 'knows' that email is valid.

You can use the .checkValidity() method of the input element (in this case, the email input field). This will return a boolean indicating wether the input is valid or not.
Here is a fiddle to play with:
http://jsfiddle.net/QP4Rc/4/
And the code:
<input id="subscribe-email" type="email" required="required" placeholder="john.doe#example.com" />
<button type="submit" id="subscribe-submit" onClick="check()">
click me
</button>
function check()
{
if(!document.getElementById("subscribe-email").checkValidity())
{
//do stuff here ie. show errors
alert("input not valid!");
}else
{
callMeIfValid();
}
}
function callMeIfValid()
{
//submit form or whatever
alert("valid input");
}

check Validate email address in JavaScript? for validation and then implement it into an if statement in your omgemailgone method (if valid continue, else do nothing)
edit:
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);
}
from the link

You can use Regular expressions to check that the email is valid on your omgemailgone() :
function omgemailgone (){
var mail = $('#subscribe-email').val();
//Example of regular expression
if(mail.match(/YourRegexp/)
{
//Do stuff
}
else alert("Invalid e-mail");
}
(using jQuery here)

u need a function that validate the email and return true or false
Validate email address in JavaScript?
<button type="submit" id="subscribe-submit" onClick="javascript:validateEmail(document.getElementById('subscribe-email').value) ? omgemailgone() : alert('email is wrong dude');" />
This is a quick solution, i recommend you to do it properly, not using inline onclick js

Related

JavaScript Login Form Not Validating

Good Evening,
I am trying to create a simple JavaScript login form that will validate by checking only 1 specific email address which has been declared and 1 password that has been declared.
However, no matter what is typed into the fields, even if nothing is present, once the submit button is clicked, the user is directed to the desired page.
I need it to only allow the desired page if the email address and password are the correct. Otherwise, notify them that it is incorrect.
Here is a link to [codepen][1] so you can see the page and script.
https://codepen.io/m0rrisim0/pen/bmzyqj
Any help is appreciated in figuring out why the script is not validating.
You have to use the attribute value from document.getElementById method,
like the following example: document.getElementById("UserName").value
function validate() {
'use strict';
var UserName = document.getElementById('UserName').value;
var email = "adrian#tissue.com";
var Password = document.getElementById('Password').value;
var pass = "welcome1";
if ((UserName == email) && (Password == pass)) {
return true;
} else {
alert("UserName and/or Password Do Not Match");
return false;
}
}
Your form's inputs lack the id atrribute and should return the function on submit event.
<form action="Issues.html" method="post" id="loginform" onsubmit="return validate()">
UserName:
<input type="text" name="UserName" id="UserName">
<br>
<br>
Password:
<input type="password" name="Password" id="Password">
<hr>
<input type="submit" value="Submit">
</form>
Your problem was getElementById(), this function requires a argument and cause a error. Because of this error the line loginform.onsubmit = validate; was never reached so the submit button submit the form without calling a validate function.
There is no need to put this line inside the if statement, but if you want you can change a little bit to getElementById without the parentesis, this way it evaluates to a function that in js is truthy.
You can check a working version of you code here:
if (document && document.getElementById) {
var loginform = document.getElementById('loginform');
loginform.onsubmit = validate;
}
https://codepen.io/francispires/pen/mzvYKX
You can improve this validation

How to correctly validate form with jQuery?

So I have this jQuery for my form:
frm.submit(function(event) {
validateForm();
if(validateForm()) {
$(this).submit();
} else {
event.preventDefault();
}
});
It does sort of work, but I get JS <error> (and it doesn't say anything else in the console about it), I think the reason is that the function has to go through the validation again? Kind of like a circular dependency.
Can you show me a better way to do the exact thing that I'm trying to achieve here please?
Validate and show errors if filled in the wrong way;
Submit the form if everything is ok
Something like this maybe?
HTML -
<input type="text" id="name" />
<input type="tel" id="phone" />
<button type="button" id="submit">Submit</button>
<div id="errors"></div>
JS -
const user = {}
$('#submit').click(function(){
// validating form
if(!$('#name').val()) {
$('#errors').text('invalid value in "name" field')
return;
}
if(!$('#phone').val()) {
$('#errors').text('invalid value in "phone" field')
return;
}
$('#errors').text('');
user.phone = $('#phone').val();
user.name = $('#name').val();
// form submission goes here
});
Logic -
Once a function returns, the execution of anything else after the return expression itself, is prevented.
If you don't return anything, the interpreter will continue to the next expression.
This gives you the option of manipulating elements and handle errors just before returning and stopping the function from continuing to run.
function validateForm(){
if (input.val().isok && select.val().ispresent){
form.submit();
}else{
show_errors();
}
}
why not that way?

JavaScript: Search string for expression and return error if not found

I have a form that should only allow e-mail addresses with a ".edu" domain, and I worked up some JavaScript to try to make that happen.
Form elements:
<input type="text" name="empEmail" id="empEmail" />
<input type="submit" name="submit" id="submit" value="submit" onClick = "error();" />
<span id="empEmailError"> </span>
JavaScript function:
//Check for non-university e-mail addresses
function error() {
var email = document.getElementById('empEmail').value;
var re = /\.edu$/;
if(!email.match(re))
{
document.getElementById('empEmailError').innerHTML = "University e-mail
address only.";
return false;
}
}
Here's the fiddle:
http://jsfiddle.net/4T5qV/
I can't get it to work. Not sure what it is I'm missing.
You have to use .test().
if(!re.test(email))
.test() returns whether the regex has matched or not.
Also, you have to use <wrap in head> option of fiddle
Demo
There was a problem where it wasnt finding the error function. It could be that it was putting the error function in a document.on('loaded') function or something like that in the jsFiddle.
So the solution is to add a function to the window, like so:
//Check for non-university e-mail addresses
window.validateEduAddress = function() {
var email = document.getElementById('empEmail').value;
var re = /\.edu$/;
if(!email.match(re)) {
document.getElementById('empEmailError').innerHTML = "University e-mail address only.";
return false;
} else {
console.log('woohoo');
}
}
Then in your html you need to tell the onclick to use that function like so:
<input type="submit" name="submit" value="submit" id="submit" onclick="validateEduAddress();" />
And just to make it easier, heres the updated jsFiddle
In general you should also try to avoid naming functions so generically, so instead of error or fail you should try to describe the event or functionality :)
As others have noted, the cause of this issue is that you have the onLoad option selected in jsfiddle, and the result is that your inline onclick handler cannot find your error function. This is partly the fault of using inline event handlers (putting the JavaScript directly in an attribute), which is not a recommended practice.
Another problem is that you have a line break right in the middle of one of your string values, and this is causing a syntax error and preventing the code from running at all.
You should use the "no wrap in <head>" option, and unobtrusive JavaScript.
Remove the onclick attribute from your element:
<input type="submit" name="submit" id="submit" value="submit" />
And use this:
function validate(e) {
var email = document.getElementById('empEmail').value,
re = /\.edu$/;
if (re.test(email)) {
document.getElementById('empEmailError').innerHTML =
"University e-mail address only.";
return false;
}
return true;
}
window.onload = function () {
var form = document.getElementById('submit').onclick = validate;
};
(I've used re.test() here as Amit suggests, because that does make more sense semantically in this case.)
http://jsfiddle.net/4T5qV/6/

javascript email validation without submitting

I want to validate this email :
<div>
<div>
<div >
<big><p>please enter an email address IF you wish to
recieve a link to your results.<p>
E-mail Address:</big> <input name="recipient"class="upload" type="text"
/>
<div id="correct">
✔
</div>
<div id="incorrect">
✘
</div>
</div>
</div>
I want to check if the email input is valid, if its is valid show the "correct" div , if not show the "incorrect" div, i want to do this without submitting the form.
cant anyone help ? thanks
Here is a function which uses Regex to match value.
<script language="javascript">
function checkEmail() {
var email = document.getElementById('recipient');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
document.getElementById('incorrect').style.visibility="visible";
document.getElementById('correct').style.visibility="hidden";
}
else
{
document.getElementById('correct').style.visibility="visible";
document.getElementById('incorrect').style.visibility="hidden";
}
}
</script>
Several alternatives/plugins/solutions for client side validation based on several JS frameworks are available. I am citing but one example that utilizes jQuery: http://speckyboy.com/2009/12/17/10-useful-jquery-form-validation-techniques-and-tutorials-2/
From this answer
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);
}

javascript - why doesnt this work?

<form method="post" action="sendmail.php" name="Email_form">
Message ID <input type="text" name="message_id" /><br/><br/>
Aggressive conduct <input type="radio" name="conduct" value="aggressive contact" /><br/><br/>
Offensive conduct <input type="radio" name="conduct" value="offensive conduct" /><br/><br/>
Rasical conduct <input type="radio" name="conduct" value="Rasical conduct" /><br/><br/>
Intimidating conduct <input type="radio" name="conduct" value="intimidating conduct" /><br/><br/>
<input type="submit" name="submit" value="Send Mail" onclick=validate() />
</form>
window.onload = init;
function init()
{
document.forms["Email_form"].onsubmit = function()
{
validate();
return false;
};
}
function validate()
{
var form = document.forms["Email_form"]; //Try avoiding space in form name.
if(form.elements["message_id"].value == "") { //No value in the "message_id"
box
{
alert("Enter Message Id");
//Alert is not a very good idea.
//You may want to add a span per element for the error message
//An div/span at the form level to populate the error message is also ok
//Populate this div or span with the error message
//document.getElementById("errorDivId").innerHTML = "No message id";
return false; //There is an error. Don't proceed with form submission.
}
}
}
</script>
Am i missing something or am i just being stupid?
edit***
sorry i should add! the problem is that i want the javascript to stop users going to 'sendmail.php' if they have not entered a message id and clicked a radio button... at the moment this does not do this and sends blank emails if nothing is inputted
You are using
validate();
return false;
...which means that the submit event handler always returns false, and always fails to submit. You need to use this instead:
return validate();
Also, where you use document.forms["Email form"] the space should be an underscore.
Here's a completely rewritten example that uses modern, standards-compliant, organised code, and works:
http://jsbin.com/eqozah/3
Note that a successful submission of the form will take you to 'sendmail.php', which doesn't actually exist on the jsbin.com server, and you'll get an error, but you know what I mean.
Here is an updated version that dumbs down the methods used so that it works with Internet Explorer, as well as includes radio button validation:
http://jsbin.com/eqozah/5
You forgot the underscore when identifying the form:
document.forms["Email_form"].onsubmit = ...
EDIT:
document.forms["Email_form"].onsubmit = function() {
return validate();
};
function validate() {
var form = document.forms["Email_form"];
if (form.elements["message_id"].value == "") {
alert("Enter Message Id");
return false;
}
var conduct = form.elements['conduct']; //Grab radio buttons
var conductValue; //Store the selected value
for (var i = 0; i<conduct.length; i++) { //Loop through the list and find selected value
if(conduct[i].checked) { conductValue = conduct[i].value } //Store it
}
if (conductValue == undefined) { //Check to make sure we have a value, otherwise fail and alert the user
alert("Enter Conduct");
return false;
}
return true;
}
return the value of validate. Validate should return true if your validation succeeds, and false otherwise. If the onsubmit function returns false, the page won't change.
EDIT: Added code to check the radio button. You should consider using a javascript framework to make your life easier. Also, you should remove the onclick attribute from your submit input button as validation should be handled in the submit even, not the button's click
Most obvious error, your form has name attribute 'Email_form', but in your Javascript you reference document.forms["Email form"]. The ironic thing is, you even have a comment in there not to use spaces in your form names :)

Categories

Resources