JS Student Email Validation - javascript

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.

Related

Want to only accept certain email address in html form

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>

How to check what <input> tag says for a password

I'm trying to make a sign-in page for my website and I wanted to make a input for my password system.
I've used the prompt() solution but it is not very efficient.
<input type="password" name="password" placeholder="Enter Password.."/>
<input type="submit" value="Login" name="login">
I know that I don't have any Javascript set up, which I'm expecting to use for this. I have a little knowledge of Javascript, not very much though. I couldn't find anything online as to the answer.
<script>
function checkpassword() {
var password = document.getElementById("password");
var pass = password.value;
if(pass == "admin"){
alert("Correct!");
}
}
<script>
<input type="password" id="password" placeholder="Password">
<button onclick="return checkpassword()">Login</button>
I have also wanted to make login page.
1) For the input I want to trigger an event function to check if password is right so I say
<input type = "password" id = "passwordInput"></input>
<button onclick = "myfunction()">Submit</button>
2) Now that I have the onclick, I need to make my function
function myfunction() {
var pass = document.getElementById("passwordInput");
//this returns the value of input
}
3) I now need to check if the password is right so I add this to myfunction()
if(pass.value == "correct password") {
alert("You have logged successfully")
}
One good website to find out how to make a login page is
https://getcodingkids.com/code-skill/create-a-password/
Use basic if statements.
HTML
<input type="password" id="password" placeholder="Enter Password.."/>
<input type="button" value="Login" name="login" onclick="checkPass(document.getElementById('password').value)"/>
JAVASCRIPT
function checkPass(pass){
if(pass == "correct pass"){
alert("Access Granted");
}
else {
alert("Please check your password");
}
}

I want to restrict users from entering number ending with 5

Here is text field.I want users to only enter value like 210,220,230,... and restrict from entering something like 215,225,...
I am looking for suggetions.I don't have much knowledge of javascript.
If you just want to prevent strings that end in '5':
document.getElementById("input").onblur = checkEND;
function checkEND() {
let firstValue = event.currentTarget.value;
if(firstValue.endsWith('5')){
warnUser()
}
}
This won't validate that the string is a valid number though.
function testInput() {
var key = window.event.keyCode;
var x = document.getElementById('textarea').value
var y = document.getElementById('textarea2').value
var z = parseInt(x, 10);
if (z+10 == y) {
document.getElementById('result').innerHTML = "valid";
} else {
document.getElementById('result').innerHTML = "invalid";
}
}
<textarea maxlength="3" id="textarea">5</textarea>
<textarea maxlength="3" id="textarea2">15</textarea>
<button onclick="testInput()">Test Input</button>
<div id="result"></div>
The first input is your first number, the second is your second number.
See Comments If Your Wondering Why This Doesn't Answer His OG Question
You can experiment with the setCustomValidity() of input elements (https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) from an onblur, onchange or oninput handler. If you are not satisfied with the value, set an error message, and an empty string otherwise. As long as the error message is set to non-empty, it is displayed and the form refuses to submit:
function check5() {
cgiftcardq.setCustomValidity(cgiftcardq.value.endsWith('5')?"Nope, it can not end with 5":"");
}
<form>
<input name="cgiftcardq" class="text_field" id="cgiftcardq" size="3" autocomplete="off" type="text" onblur="check5()">
<input type="submit" value="Send">
</form>
(StackOverflow snippets interfere with form submission - probably as part of security -, so successful submission just makes the form disappear)
As setCustomValidity() does not work everywhere (according to the compatibility table, it will not work on non-Andorid mobiles), classic "budget" solution may be mentioned too: you can simply disable the send button as long as you are not satisfied with the input:
function check5() {
if(cgiftcardq.value.endsWith('5')){
send.disabled=true;
message.innerHTML="Nope, it can not end with 5";
} else {
send.disabled=false;
message.innerHTML="OK";
}
}
<form>
<input name="cgiftcardq" class="text_field" id="cgiftcardq" size="3" autocomplete="off" type="text" oninput="check5()">
<input id="send" type="submit" value="Send" disabled>
</form>
<div id="message"></div>

Showing all error messages at the same time in form validation

Why are my conditional statements not working properly? I want to display bothe error messages at the same time.
function validate() {
if (firstName.value == "") {
document.getElementById('error').innerHTML = "*Field is empty";
return false;
} else if (lastName.value == "") {
document.getElementById('errorTwo').innerHTML = "*Field is empty";
return false;
} else {
return true;
}
}
<form name="form" action="action.php" method="post" onsubmit="return validate()">
<div class="wrapper">
<span>Name</span>
<br>
<input type="text" name="firstName" id="firstName" placeholder="First Name" onfocus="this.placeholder=''" onblur="this.placeholder='First Name'" />
<label id="error"></label>
<br>
<input type="text" name="middleName" id="middleName" placeholder="Middle Name (optional)" onfocus="this.placeholder=''" onblur="this.placeholder='Middle Name (optional)'" />
<input type="text" name="lastName" id="lastName" placeholder="Last Name" onfocus="this.placeholder=''" onblur="this.placeholder='Last Name'" />
<label id="errorTwo"></label>
<br>
<br>
</div>
Your conditional statements are working correctly, your understanding of them is a little off though.
An if / else if statement will stop running when a condition is matched, so if firstName.value is empty, then that if statement will be matched and the code will exit there and not evaluate the rest of the conditions.
You want to use independent conditional statements for each test, and instead of returning either true or false, set a variable to true or false and return that after the conditional checks.
So...
function validate()
{
var valid = true;
if(firstName.value=="")
{
document.getElementById('error').innerHTML="*Field is empty";
valid = false;
}
if(lastName.value=="")
{
document.getElementById('errorTwo').innerHTML="*Field is empty";
valid = false;
}
return valid;
}
Just a note on the code itself, the above comments are mainly correct, if you post your entire code, you'll probably get more helpful responses. Also, you can eliminate the =="" part of the checks and just test the value of the variable as an empty string evaluates to false.
Don't chain the validations together with if-else otherwise if the first name validation fails, then you will never check the last name validation.
Help yourself by quickly creating a JsFiddle :-)
Here it is:
http://jsfiddle.net/23tnpve4/1/
You will easily see some issues by trying:
As others mentioned, missing brackets etc
As others mentioned, if the first test fails the other fields are not checked so errors can by corrected only step by step.
There is no code that refreshes your error DIVs. In a new form check, the error fields have to be cleared first. Checking forms are cycles with several possible start statuses.
Try to collect the status of fields in an array and work them later, something like this:
window.validate = function()
{
var firstName = document.getElementById('firstName');
var lastName = document.getElementById('lastName');
// Clear
firstName.val('');
lastName.val('');
// Check
var errorNames = [];
if(firstName.value=="")
{
errorNames.push('firstName');
}
if(lastName.value=="")
{
errorNames.push('lastName');
}
// Inform
for (var i=0; i<errorNames.length; i++) {
document.getElementById(errorNames[i]).innerHTML="*Field is empty";
}
// Return value
return errorNames.length == 0;
}
The concept of this code will work more intuitively. I haven't checked it against typos, it is a draft, but I do hope it will help you.

Set custom HTML5 required field validation message

Required field custom validation
I have one form with many input fields. I have put html5 validations
<input type="text" name="topicName" id="topicName" required />
when I submit the form without filling this textbox it shows default message like
"Please fill out this field"
Can anyone please help me to edit this message?
I have a javascript code to edit it, but it's not working
$(document).ready(function() {
var elements = document.getElementsByName("topicName");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("Please enter Room Topic Title");
}
};
elements[i].oninput = function(e) {
e.target.setCustomValidity("");
};
}
})
Email custom validations
I have following HTML form
<form id="myform">
<input id="email" name="email" type="email" />
<input type="submit" />
</form>
Validation messages I want like.
Required field: Please Enter Email Address
Wrong Email: 'testing#.com' is not a Valid Email Address. (here, entered email address displayed in textbox)
I have tried this.
function check(input) {
if(input.validity.typeMismatch){
input.setCustomValidity("'" + input.value + "' is not a Valid Email Address.");
}
else {
input.setCustomValidity("");
}
}
This function is not working properly, Do you have any other way to do this? It would be appreciated.
Code snippet
Since this answer got very much attention, here is a nice configurable snippet I came up with:
/**
* #author ComFreek <https://stackoverflow.com/users/603003/comfreek>
* #link https://stackoverflow.com/a/16069817/603003
* #license MIT 2013-2015 ComFreek
* #license[dual licensed] CC BY-SA 3.0 2013-2015 ComFreek
* You MUST retain this license header!
*/
(function (exports) {
function valOrFunction(val, ctx, args) {
if (typeof val == "function") {
return val.apply(ctx, args);
} else {
return val;
}
}
function InvalidInputHelper(input, options) {
input.setCustomValidity(valOrFunction(options.defaultText, window, [input]));
function changeOrInput() {
if (input.value == "") {
input.setCustomValidity(valOrFunction(options.emptyText, window, [input]));
} else {
input.setCustomValidity("");
}
}
function invalid() {
if (input.value == "") {
input.setCustomValidity(valOrFunction(options.emptyText, window, [input]));
} else {
input.setCustomValidity(valOrFunction(options.invalidText, window, [input]));
}
}
input.addEventListener("change", changeOrInput);
input.addEventListener("input", changeOrInput);
input.addEventListener("invalid", invalid);
}
exports.InvalidInputHelper = InvalidInputHelper;
})(window);
Usage
→ jsFiddle
<input id="email" type="email" required="required" />
InvalidInputHelper(document.getElementById("email"), {
defaultText: "Please enter an email address!",
emptyText: "Please enter an email address!",
invalidText: function (input) {
return 'The email address "' + input.value + '" is invalid!';
}
});
More details
defaultText is displayed initially
emptyText is displayed when the input is empty (was cleared)
invalidText is displayed when the input is marked as invalid by the browser (for example when it's not a valid email address)
You can either assign a string or a function to each of the three properties.
If you assign a function, it can accept a reference to the input element (DOM node) and it must return a string which is then displayed as the error message.
Compatibility
Tested in:
Chrome Canary 47.0.2
IE 11
Microsoft Edge (using the up-to-date version as of 28/08/2015)
Firefox 40.0.3
Opera 31.0
Old answer
You can see the old revision here: https://stackoverflow.com/revisions/16069817/6
You can simply achieve this using oninvalid attribute,
checkout this demo code
<form>
<input type="email" pattern="[^#]*#[^#]" required oninvalid="this.setCustomValidity('Put here custom message')"/>
<input type="submit"/>
</form>
Codepen Demo: https://codepen.io/akshaykhale1992/pen/yLNvOqP
HTML:
<form id="myform">
<input id="email" oninvalid="InvalidMsg(this);" name="email" oninput="InvalidMsg(this);" type="email" required="required" />
<input type="submit" />
</form>
JAVASCRIPT :
function InvalidMsg(textbox) {
if (textbox.value == '') {
textbox.setCustomValidity('Required email address');
}
else if (textbox.validity.typeMismatch){{
textbox.setCustomValidity('please enter a valid email address');
}
else {
textbox.setCustomValidity('');
}
return true;
}
Demo :
http://jsfiddle.net/patelriki13/Sqq8e/
Try this:
$(function() {
var elements = document.getElementsByName("topicName");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("Please enter Room Topic Title");
};
}
})
I tested this in Chrome and FF and it worked in both browsers.
Man, I never have done that in HTML 5 but I'll try. Take a look on this fiddle.
I have used some jQuery, HTML5 native events and properties and a custom attribute on input tag(this may cause problem if you try to validade your code). I didn't tested in all browsers but I think it may work.
This is the field validation JavaScript code with jQuery:
$(document).ready(function()
{
$('input[required], input[required="required"]').each(function(i, e)
{
e.oninput = function(el)
{
el.target.setCustomValidity("");
if (el.target.type == "email")
{
if (el.target.validity.patternMismatch)
{
el.target.setCustomValidity("E-mail format invalid.");
if (el.target.validity.typeMismatch)
{
el.target.setCustomValidity("An e-mail address must be given.");
}
}
}
};
e.oninvalid = function(el)
{
el.target.setCustomValidity(!el.target.validity.valid ? e.attributes.requiredmessage.value : "");
};
});
});
Nice. Here is the simple form html:
<form method="post" action="" id="validation">
<input type="text" id="name" name="name" required="required" requiredmessage="Name is required." />
<input type="email" id="email" name="email" required="required" requiredmessage="A valid E-mail address is required." pattern="^[a-zA-Z0-9_.-]+#[a-zA-Z0-9-]+.[a-zA-Z0-9]+$" />
<input type="submit" value="Send it!" />
</form>
The attribute requiredmessage is the custom attribute I talked about. You can set your message for each required field there cause jQuery will get from it when it will display the error message. You don't have to set each field right on JavaScript, jQuery does it for you. That regex seems to be fine(at least it block your testing#.com! haha)
As you can see on fiddle, I make an extra validation of submit form event(this goes on document.ready too):
$("#validation").on("submit", function(e)
{
for (var i = 0; i < e.target.length; i++)
{
if (!e.target[i].validity.valid)
{
window.alert(e.target.attributes.requiredmessage.value);
e.target.focus();
return false;
}
}
});
I hope this works or helps you in anyway.
This works well for me:
jQuery(document).ready(function($) {
var intputElements = document.getElementsByTagName("INPUT");
for (var i = 0; i < intputElements.length; i++) {
intputElements[i].oninvalid = function (e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
if (e.target.name == "email") {
e.target.setCustomValidity("Please enter a valid email address.");
} else {
e.target.setCustomValidity("Please enter a password.");
}
}
}
}
});
and the form I'm using it with (truncated):
<form id="welcome-popup-form" action="authentication" method="POST">
<input type="hidden" name="signup" value="1">
<input type="email" name="email" id="welcome-email" placeholder="Email" required></div>
<input type="password" name="passwd" id="welcome-passwd" placeholder="Password" required>
<input type="submit" id="submitSignup" name="signup" value="SUBMIT" />
</form>
You can do this setting up an event listener for the 'invalid' across all the inputs of the same type, or just one, depending on what you need, and then setting up the proper message.
[].forEach.call( document.querySelectorAll('[type="email"]'), function(emailElement) {
emailElement.addEventListener('invalid', function() {
var message = this.value + 'is not a valid email address';
emailElement.setCustomValidity(message)
}, false);
emailElement.addEventListener('input', function() {
try{emailElement.setCustomValidity('')}catch(e){}
}, false);
});
The second piece of the script, the validity message will be reset, since otherwise won't be possible to submit the form: for example this prevent the message to be triggered even when the email address has been corrected.
Also you don't have to set up the input field as required, since the 'invalid' will be triggered once you start typing in the input.
Here is a fiddle for that: http://jsfiddle.net/napy84/U4pB7/2/
Hope that helps!
Just need to get the element and use the method setCustomValidity.
Example
var foo = document.getElementById('foo');
foo.setCustomValidity(' An error occurred');
Use the attribute "title" in every input tag and write a message on it
you can just simply using the oninvalid=" attribute, with the bingding the this.setCustomValidity() eventListener!
Here is my demo codes!(you can run it to check out!)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>oninvalid</title>
</head>
<body>
<form action="https://www.google.com.hk/webhp?#safe=strict&q=" method="post" >
<input type="email" placeholder="xgqfrms#email.xyz" required="" autocomplete="" autofocus="" oninvalid="this.setCustomValidity(`This is a customlised invalid warning info!`)">
<input type="submit" value="Submit">
</form>
</body>
</html>
reference link
http://caniuse.com/#feat=form-validation
https://www.w3.org/TR/html51/sec-forms.html#sec-constraint-validation
You can add this script for showing your own message.
<script>
input = document.getElementById("topicName");
input.addEventListener('invalid', function (e) {
if(input.validity.valueMissing)
{
e.target.setCustomValidity("Please enter topic name");
}
//To Remove the sticky error message at end write
input.addEventListener('input', function (e) {
e.target.setCustomValidity('');
});
});
</script>
For other validation like pattern mismatch you can add addtional if else condition
like
else if (input.validity.patternMismatch)
{
e.target.setCustomValidity("Your Message");
}
there are other validity conditions like rangeOverflow,rangeUnderflow,stepMismatch,typeMismatch,valid
use it on the onvalid attribute as follows
oninvalid="this.setCustomValidity('Special Characters are not allowed')

Categories

Resources