Want to only accept certain email address in html form - javascript

I'm creating a form where only a certain email address is accepted. If the wrong address is used, then a message should appear.
I want to use something like ".pattern != email" within my script, however I understand this attribute can only be used within input. I've tried to use .match as well without any success.
This is a snippet of the form:
<form onsubmit="return validation()">
<label for="email"> <b> Email: </b> </label>
<input type="email" name="email" id="emailinput" placeholder="Please enter email"
pattern=".+#gmail.com"> <span id="message"></span>
</form>
The relevant script:
<script>
funcion validation() {
if (document.getElementById("emailinput").pattern != ".+#gmail.com") {
document.getElementById("message").innerHTML
= "<em> Must be a gmail '#gmail.com' account </em>";
return false;
else
return true;}
</script>

#(gmail.com) will match #gmail.com specifically...
# matches the # symbol
Something like [a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+[\S] for the portion before your # section may work...
[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+[\S]#(gmail.com)
Run your email through a function and return regex.test(email), this will return a Boolean value that can be used in a conditional.
let email = document.getElementById('email');
let b = document.getElementById('b');
const emailIsValid = (email) => {
return /[\S]+#(gmail.com)/.test(email)
}
b.addEventListener('click', function() {
emailIsValid(email.value)?
console.log(emailIsValid(email.value)):
console.log(emailIsValid(email.value) + ': ' + email.value + ' is not valid gmail address!');
})
Enter an email: <input id="email"> <button id="b">Test It</button>

Related

JS Student Email Validation

I am a beginner in Javascript and am looking to find a solution to why the code below is not working.
I've reviewed several tutorials here on StackOverflow and believe it should work... but it's not.
The HTML looks like this:
<form id="personalInfo">
<h2>Email: </h2>
<input type="text" name="Email" id="Email">
<br>
</form>
<input type="button" onclick = "validateEmail()">
The Javascript looks like this:
function validateEmail()
{
var reg = /^([A-Za-z0-9_\-\.]){1,}\#([A-Za-z0-9_\-\.]){1,}\.([A-Za-z]{2,4})$/;
var address = document.forms[personalInfo].elements[Email].value;
if (reg.test(address) == false) {
alert ("Email not valid");
return false;
}
return true;
}
By my accounts, this should pop up an alert if the email address entered by the user is not valid.
Instead, nothing happens at all. I'm not sure if the test is even run.
function validateEmail() {
// There are, I feel, better version of this regex online
// You can check "https://emailregex.com/"
var reg = /^([A-Za-z0-9_\-\.]){1,}\#([A-Za-z0-9_\-\.]){1,}\.([A-Za-z]{2,4})$/;
// document.getElementById() - Easier to read & understand, and more widely used
var address = document.getElementById('Email').value;
// Corrected your returns - not the main issue in the function, but the old
// returns might have caused confusion
if (reg.test(address) == false) {
alert("Email not valid");
return false
}
return true
}
<form id="personalInfo">
<h2>Email: </h2>
<input type="text" name="Email" id="Email">
</form>
<!-- You had a typo on the onclick but has since been fixed -->
<input type="button" onclick="validateEmail()" value="Submit">
Two issues here:
1- In your HTML, you are missing an = sign here: onclick"validateEmail()" (Edit: seems you fixed it now)
2- in your Javascript, the indices personalInfo and Email are strings, wrap them in quotation marks:
var address = document.forms['personalInfo'].elements['Email'].value;
function validateEmail()
{
var reg = /^([A-Za-z0-9_\-\.]){1,}\#([A-Za-z0-9_\-\.]){1,}\.([A-Za-z]{2,4})$/;
var address = document.forms['personalInfo'].elements['Email'].value;
if (reg.test(address)== false)
{
alert ("Email not valid");
return false
}
return true;
}
<form id="personalInfo">
<h2>Email: </h2> <input type="text" name="Email" id="Email"> <br>
</form>
<input type="button" onclick="validateEmail()">
When dealing with email inputs, set the input type to email instead of text - like so:
<input name="my-email" type="email" />"
Then the browser will perform validation on the input; such as if the input doesn't have the # present.

Use JavaScript to change the href Tag depending on input field

I want to make the link in this change depending on whether the password is correct. I want to set one password and I only know html and minimal JS. I think I have it set so that when the password is wima it will change the href and allow the link to work. That doesn’t happen. Can I have some help?
function login()
var password = getElementById("password"); {
if (password = "wima") {
getElementById("submit").href = "/pages/home.html";
} else {
getElementById("submit").href = "index.html";
}
}
<p>
Username
<input id="username" type=text placeholder="WIMA"><br> Password
<input id="password" type=password placeholder="WIMA"><br>
<a class="button" id="submit" href="#" onclick="login()">
Submit
</a>
</p>
There are a few issues with your JavaScript.
<script language="JavaScript">
function login()
var password = getElementById("password"); // this gets the element, not the value of the element
{ // this curly brace is in the wrong place
if (password = "wima") { // this sets the value of the password var to "wima"
getElementById("submit").href="/pages/home.html";
}
else {
getElementById("submit").href="index.html";
}
}
</script>
Here is your code, cleaned up.
<script language="JavaScript">
function login() {
var password = document.getElementById("password").value;
if (password == "wima") { // use == to compare value
document.getElementById("submit").href="/pages/home.html";
}
else {
document.getElementById("submit").href="index.html";
}
}
</script>
Another issue here is that you shouldn't be changing the href on the element used to execute the login() function.
You could redirect the user to the new page like so:
<script language="JavaScript">
function login() {
var password = document.getElementById("password").value;
if (password == "wima") {
window.location.href="/pages/home.html";
}
else {
window.location.href="index.html";
}
}
</script>
I guess you are doing it wrong if you want to change the href value based upon input type text. You should make a blur/change event on password input text. Based upon password value when user clicks on href he should be redirected accordingly.
Check this out:
function login() {
var _password = document.getElementById("password").value;
if ("wima" == _password) {
document.getElementById("submit").href = "/pages/home.html";
} else {
document.getElementById("submit").href = "index.html";
}
}
<p>
Username
<input id="username" type=text placeholder="WIMA">
<br> Password
<input id="password" type=password placeholder="WIMA" onblur="login()">
<br>
<a class="button" id="submit" href="#">
Submit
</a>
</p>
Here is a form validator with a switch.
function validateForm() {
var x = document.forms["myForm"]["password"].value;
switch (x) {
case "":
alert("Name must be filled out");
return false;
break;
case "wima":
return true;
break;
default:
alert("Error: Wrong Password.");
document.location.href = "https://stackoverflow.com/search?q=notloggedin";
// Replace the link above with your error link return
return false;
}
}
<!-- Replace action link with your successful link -->
<form name="myForm" action="https://stackoverflow.com/search?q=login" onsubmit="return validateForm()" method="post">
<input type="password" name="password">
<input type="submit" value="Submit">
</form>
Your password is visible in text if someone inspects the html/javascript. So this method of security is not advised. For basic concepts it is interesting to have a link change based on input. Try this.
<p>
Username
<input id="username" type="text" placeholder="WIMA"><br> Password
<input id="password" type="password" placeholder="WIMA"><br>
<a class="button" id="submit" >
Submit
</a>
</p>
<script>
var password = document.getElementById('password');
password.addEventListener('change', enableLogin);
var submit = document.getElementById('submit');
function enableLogin() {
if (password.value == "wima") { // it is an easy mistake (= or ==)
submit.href = "/pages/home.html";
} else {
submit.removeAttribute('href');
}
}
</script>
A few things happened here:
The value inside a <input> is accessed by .value;
You misplaced the {
getElementById is not a global method it has to be called on the element you want to select in (in your case the document itself)
To test if two values are equal use === in js
function login() {
var password = document.getElementById("password").value;
if (password === "wima") {
document.getElementById("submit").href = "/pages/home.html";
} else {
document.getElementById("submit").href = "index.html";
}
}
<p>
Username
<input id="username" type="text" placeholder="WIMA"><br> Password
<input id="password" type="password" placeholder="WIMA"><br>
<a class="button" id="submit" href="#" onclick="login()">
Submit
</a>
</p>

How to change errorMess value based on a condition in form-validator jquery plugin

I am trying to validate a form using jquery form validator plugin. I want to display custom messages like if the email is not given then it should display email address is required, if email value is not a valid one then it should display invalid email address. But in both cases, it is giving me the same default message like 'You have not given a correct e-mail address'. I tried to like this
<form action="" id="registration-form">
<p>E-mail
<input name="email" id="email" data-validation="email" >
</p>
<p>
<input type="submit" value="Validate">
<input type="reset" value="Reset form">
</p>
</form>
The script is
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.20/jquery.form-validator.min.js"></script>
$.validate({
onElementValidate : function(valid, $el, $form, errorMess) {
if ($el.attr('name') == 'email') {
alert('Input ' +$el.attr('name')+ ' is ' + ( valid ? 'VALID':'NOT VALID') );
var value = $('#email').val();
if (value) {
var filter=/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
if (! filter.test(value)) {
alert('invalid');
errorMess = 'invalid email';
}
} else {
alert('no mail');
errorMess = 'no email';
}
}
alert('errorMess :: ' + errorMess);
$('.help-block form-error').html(errorMess);
},
borderColorOnError: '#b94a48',
errorMessagePosition : 'inline',
modules : 'location, date, security, file',
onModulesLoaded : function() {
$('#country').suggestCountry();
}
});
It is pretty simple, adding multiple values in data-validation will actually done the magic.
<input name="email" id="email" data-validation="required, email" >

Validating form using HTML and JavaScript - Checking form input matches a value in an array

I have a simple web form which accepts a user email and password for log in.
I want to check the users email and password match up with what is stored in an external javascript file and if the combination matches then proceed to the index.html page.
My array is declared in my router file as follows:
var USERS = { users: [] };
function User(type, useremail, password) {
this.type = type;
this.useremail = useremail;
this.password = password;
}
var Bob = new User("rep", "bob#bob.com", "qwerty");
USERS.users.push(Bob);
var Helen = new User("rep", "helen#helen.com", "test");
USERS.users.push(Helen);
var Dominic = new User("customer", "dom#dom.com", "1234");
USERS.users.push(Dominic);
var James = new User("grower", "james#james.com", "pass1");
USERS.users.push(James);
My html form is as follows:
<div id="loginform">
<form id ="login" name="login" method="post" accept-charset="utf-8" onsubmit="return verify();">
<h1> </h1>
<label>
<span>Email Address:</span>
<input id="email" type="email" name="email" placeholder="Enter a valid email address" required />
</label>
<br>
<label>
<span>Password:</span>
<input id="password" type="password" name="password" placeholder="Password" required />
</label>
<br> <br>
<label id="reset">Click here to reset your password
</label>
<br>
<label>
<span> </span>
<input id="submit_button" type="submit" value="Login" />
</label>
<!-- <input type="submit" value="Login" onsubmit = "verify()"> --><!-- <input type="submit" name="submit" value="Send"> -->
</form> <!-- End of log in form -->
</div>
My attempt at checking if the user email and password combo match:
function verify() {
validUser = false;
for (var x in USERS.users){
//console.log(USERS.users[x].userid);
if (query.useremail === USERS.users[x].useremail
&& query.password === USERS.users[x].password)
{
validUser = true;
break;
} // end of if
}// end of for
console.log(validUser);
if (validUser === true){
console.log("logged in");
res.render('index.html');
}
}
Just in case you need to see it, a section in my router where I feedback the log in page on request:
app.get('/views/login.html', function (req, res) {
res.render('../views/login.html');
//console.log("Log in page displayed");
});
app.post('/views/login.html', function (req, res) {
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
console.log(query);
console.log("Username: " + query.useremail);
console.log("Password: " + query.password);
});
I've confused myself with all the different codes and files ... How do I go about verifying that the user can log in?
Where do I put my verify() function? I currently have it within the router file below the user data - but I want to use it within HTML so I was considering putting into tags there...?
I supose that you use Javascript as server with NodeJS, then you need to create a route for <form id ="login" action="path"... wiht method POST. In the server:
app.post([path type on action], function(req, res) {
verify();
}
You catch input values: req.body.[attr name of input]. For example, for email:
var email = req.body.email;

Form only validates one field with javascript

I'm trying to make a simple register form that makes sure the username and password have been entered correctly before submitting. Here's my form:
<form id="register" name="register" action="" method="POST" onsubmit="return validate_account_creation(this)">
<label> Username
<input type="text" name="username" />
</label>
<label> Password
<input type="text" name="password" />
</label>
<input type="submit" name="submit" value="Submit" class="button"/>
</form>
And here are my javascript functions:
function validate_username(username) {
var regex = /[a-zA-Z0-9\-\_]{5,15}/g;
var str = username;
if (!regex.test(str)) {
alert("Your username must be between 5 and 15 characters in length");
register.username.focus();
return false;
}
}
function validate_password(password) {
regex = /[a-zA-Z]{5,}[0-9]{1,}/g;
str = password;
if (!regex.test(str)) {
alert("Your password must be at least 6 characters in length and must contain at least 1 number");
register.password.focus();
return false;
}
}
//Validate register form
function validate_account_creation(form) {
return validate_username(form.username.value);
return validate_password(form.password.value);
return true;
}
The username function works fine and it validates that one every time. However, if the username is correct, the form submits. The second function never activates. If the first function doesn't return anything, shouldn't the second function then be called and validate the second field?
It's the return statements. A return aborts the rest of the function and returns the result, so your validation should look like:
Javascript
function validate_account_creation(form) {
var username = validate_username(form.username.value);
var password = validate_password(form.password.value);
return username && password; // if both are true, submit form
}

Categories

Resources