class name not showing when trying to validate email - javascript

I have a form the is trying to validate email. If the email is incorrect the class for the input does not show. Below is the code for the html:
<div class="email-entry desktop-container">
<div id="a"></div>
<form name="form1" action="#">
<input id="test" type="text" name="text1" placeholder="Email Address" value="" onclick="return ValidateEmail(document.form1.text1)">
<input type="image" src="images/icon-arrow.svg" alt="submit">
<p id="addedText"></p>
</form>
and below I have implemented the following javascript:
function ValidateEmail(inputText) {
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (inputText.value.match(mailformat)) {
alert("You have entered a correct email addresss")
document.form1.text1.focus();
return true;
} else {
// var img = document.createElement('img');
// img.src = "/images/icon-error.svg"
document.getElementById("addedText").innerHTML += "This is the wrong email address";
document.getElementByClassName("invalidEmail")
// alert("You have entered an invalid email address!");
document.form1.text1.focus();
return false;
}
}
the css I am trying to activate is the following:
.invalidEmail {
border: 1px solid red;
background-image: url("/images/icon-error.svg");
background-repeat: no-repeat;
background-position: 75% 25%;
}
At the end of the day I want the an image to appear in the form like this. . The issue is nothing seems to appear.

To add a class to your input element, you need to use element.classList.add and to remove it you need element.classList.remove.
Also, document.getElementsByClassName("invalidEmail") will get you all the elements which contain invalidEmail classname. So it is not required here
Have gone through the repo which you mentioned:
CSS specificity is one of the culprit here. Adding !important will work fine now (check border in the snippet) but ideally you should read about it and then fix the css without using !important
It seems you are not hosting your project and opening the index.html file directly. Host your project on some server (e.g. localhost) and it should work fine (python -m SimpleHTTPServer is a simple command to help you spawn a local server quickly which you can use but there are others as well).
function ValidateEmail was not using proper regex test for email testing. Read here for more details
Have tried to fix it for you
function ValidateEmail(inputText) {
var mailformat = /^(([^<>()\[\]\\.,;:\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,}))$/;;
if (mailformat.test(inputText.value)) {
document.getElementById("addedText").innerHTML = "";
alert("You have entered a correct email addresss")
//document.form1.text1.focus();
document.getElementById("test").classList.remove("invalidEmail")
return true;
} else {
// var img = document.createElement('img');
// img.src = "/images/icon-error.svg"
document.getElementById("addedText").innerHTML = "This is the wrong email address";
document.getElementById("test").classList.add("invalidEmail")
// alert("You have entered an invalid email address!");
document.form1.text1.focus();
return false;
}
}
.invalidEmail {
border: 1px solid red !important;
/*Check here*/
background-image: url("https://image.flaticon.com/icons/png/128/752/752755.png");
background-repeat: no-repeat;
background-position: 75% 25%;
background-size: 12px 12px;
}
<div class="email-entry desktop-container">
<div id="a"></div>
<form name="form1" action="#">
<input id="test" type="text" name="text1" placeholder="Email Address" value="" onclick="return ValidateEmail(document.form1.text1)">
<input type="image" src="images/icon-arrow.svg" alt="submit" >
<p id="addedText"></p>
</form>
</div>
Hope it helps. Revert for any doubts.
Note: This is how icon image and red boundary is coming for me

Related

Input user name and email id and download pdf certificate with same name (name+emailid) from a folder

Can you correct the code below so that a user inputs his firstname and email id and his PDF certificate with same (firstname and email id) is downloaded from OOEcertificate folder
Call a JavaScript function
function myFunction()
{
var downloadUrl = document.getElementById("url").value;
document.getElementById("downlod").href = '/ooecertificate' + downloadUrl + '.pdf';
}
alert("You are Successfully Called the JavaScript function");
}
<div>
<label>ENTER YOUR REGISTRATION ID:</label>
<br> </br>
<label>(Your registration id is your firstname+registered email id:
for example if your name is SAMMY DIXIT and
your registered email id is SAMMY.DIXIT#GMAIL.COM
your REGISTRATION ID WILL BE: SAMMYSAMMY.DIXIT#GMAIL.COM
</label>
<input type="text" name="url" id="url" onkeyup="myFunction()">
<a href="/OOEcertificate" id="downlod" download><span>Download</span></a>
</div>
</div>
This is a demo starting from your code that will fetch the value from the input box #url and will use that value to compose the url string that will be used to navigate the browser to the pdf download.
Such behaviour is obtained with window.location.href that I commented to make the demo working here. On its behalf it will show the url in the console.
function downloadPdf(){
//fetch the registrationId from the input#url
let registrationId = document.getElementById("url").value;
//transform the registrationId string to lower case
registrationId = registrationId.trim().toLowerCase();
const pdfUrl = `/ooecertificate/${registrationId}.pdf`;
//this is the statement to redirect the browser to the wanted url
//now commented because it wouldn't work here on the snippet
//window.location.href = pdfUrl;
//on its behalf I'm writing the url on console
console.log(pdfUrl);
}
label.fieldLabel{
display: block;
margin-bottom: 1rem;
}
label.fieldDescription{
display: block;
margin-bottom: 1rem;
border: solid 1px gray;
padding: 1em;
}
button{
cursor: pointer;
}
<div>
<label class="fieldDescription">
Your registration id is your firstname+registered email id:<br>
For example..<br>
if your name is SAMMY DIXIT and your registered email id is SAMMY.DIXIT#GMAIL.COM<br>
your REGISTRATION ID WILL BE: <b>sammysammy.dixit#gmail.com</b>
</label>
<label class="fieldLabel">ENTER YOUR REGISTRATION ID:</label>
<input type="text" name="url" id="url">
<button onclick="downloadPdf();">Download</button>
</div>

document.getElementById JS HTML CSS

I am trying to get my forms NOT TO reset. I am making a <input type="password" /> and whenever I click the button to submit the password, and they get it wrong, I need there to be something that shows that it is incorrect. It works, but only for a split second. Can you help me?
function desktop() {
var pass = document.getElementById("pass").value;
if (pass == "555") {
alert("Welcome;")
} else {
document.getElementById("wrg").innerHTML = "Incorrect Password";
}
}
#pass {
border-radius: 8px;
padding: 5px;
margin-bottom: 5px;
}
#user {
margin-bottom: 10px;
padding-bottom: 0px;
margin-top: 220px;
}
#wrg {
visibility: visible;
}
<form>
<center>
<h1 id="user">User</h1>
<input type="password" id="pass" placeholder=" Password" /><br>
<button onclick="desktop()" id="pass">Sign In</button>
<p id="wrg"></p>
</center>
</form>
The button ends up submitting the form, which causes the window to refresh because there's no action attribute on the form.
You can prevent this by either making the button type="button" (rather than the default submit), using event.preventDefault(), or by returning false, as below. (But as noted in comments below, return false may not be the best approach: it's easy to forget to include the return in both the function and the onclick attribute, without which the form will submit anyway. event.preventDefault is the most explicit and therefore probably best way to handle this.)
function desktop() {
var pass = document.getElementById("pass").value;
if (pass == "555") {
alert("Welcome;")
} else {
document.getElementById("wrg").innerHTML = "Incorrect Password";
}
return false;
}
#pass {
border-radius: 8px;
padding: 5px;
margin-bottom: 5px;
}
#user {
margin-bottom: 10px;
padding-bottom: 0px;
/*margin-top: 220px;*/
}
<form>
<center>
<h1 id="user">User</h1>
<input type="password" id="pass" placeholder=" Password" /><br>
<button onclick="return desktop()">Sign In</button>
<p id="wrg"></p>
</center>
</form>
(You do have duplicate pass IDs, which should be unique, and of course clientside authentication as done here isn't the least bit secure, but neither of those issues is directly relevant to your question. getElementById winds up returning the first matching element, which happens to be the one you wanted.)
You are using duplicate IDs for your button and input elements: pass.
Also, it would be easier to just add an event listener to the Sign In button and capture that event inside your function.
document.getElementById("pass").addEventListener('click', desktop);
function desktop(evt) {
evt.preventDefault();
var pass = document.getElementById("pass").value;
if (pass == "555") {
alert("Welcome;");
} else {
document.getElementById("wrg").innerHTML = "Incorrect Password";
}
}
If you do it this way, remember to remove the onclick attribute from the button.

Simplest way to change the border of a textfield on error

I am trying to figure out the easiest way to put a red border around a text field if it doesn't follow a specific format. My code is property detecting if the text is in the correct format but I am having trouble changing the border color when the check fails. I would prefer to only use html/css and JavaScript if possible but I can't seem to figure out how to do that.
This is my html for the text box:
<p class="fieldtitle"> First Name </p>
<span><input type="text" class="textinput" id="fname" name="fname" /></span>
This is my JavaScript to check if it's in the correct format:
function chkfName() {
var myfname = document.getElementById("fname");
var pos = myfname.value.search(/^[A-Z][a-z]+$/);
if (pos != 0) {
//this is where I want to change the border around the text box
return false;
} else
return true;
}
You can change it pretty easily like this!
function chkfName() {
var myfname = document.getElementById("fname");
var pos = myfname.value.search(/^[A-Z][a-z]+$/);
if (pos != 0) {
fname.style.borderColor = "red";
return false;
} else
return true;
}
Here is some documentation on it: http://www.w3schools.com/js/js_htmldom_css.asp
Create a stylesheet class .error
Toggle it with JS using Element.classlist.toggleDocs
function chkfName() {
var fname = document.getElementById("fname");
var pos = /^[\w'-]{2,32}$/.test(fname.value);
fname.classList.toggle("error", !pos);
return pos;
}
document.forms[0].addEventListener("submit", chkfName);
.error{border:2px solid red;}
<form>
<p class="fieldtitle"> First Name </p>
<span><input type="text" class="textinput" id="fname" name="fname" /></span>
<input type="submit" value="Test">
</form>
I would kindly discourage you from using [A-Z][a-z]+, a person name like Đuro will return a nice error since not an A-Z character.
Also, I'd use .trim() and convert the first character automatically to uppercase - for a better user experience. Seeing roko being converted automatically to Roko from your program - without throwing nonsense errors and stopping my progress - would be quite a nice experience.
In any way you should find a better regex.
For info, since it doesn't give any javascript hints:
HTML5 allows to test a pattern with the attribute pattern:
If maybe not to be used in real life yet, it is a fast way to test your regular expression.
https://www.w3.org/TR/html-markup/datatypes.html#form.data.pattern
https://www.w3.org/wiki/HTML/Elements/input/text
http://caniuse.com/#feat=input-pattern
input:valid {/* empty doesn't trigger errors, so it is valid :( unless required */
border-color:green;
box-shadow:0 0 0 3px green;
}
input:invalid {
border-color:red;
box-shadow:0 0 0 3px tomato
}
<form>
<p>The pattern from your question</p>
<input type="text" name="test" pattern="^[A-Z][a-z]+$" placeholder="^[A-Z][a-z]" required />
</form>

Printing text next to a form field in JavaScript

I'm having a bit of trouble with this assigment and would like your help.
We are meant to create a product registration form page with all the regular expressions and everything and display the correct error when the regexes don't match.
I am trying to print a tick or say OK next to a form field but I can't get the right function. My form right now looks like this: http://www.imageurlhost.com/images/98zrdmrmsvbxnwowrvsf.png
The "Please enter product ...." is activated by jquery with a slideUp and slideDown function with onblur on the text field.
So I want to display OK where the red circle is after you click away from it, and then if you change it to something that doesn't match the OK disappears and my alert shows up. So this is my code so far:
My html form:
<div>
<input type="text" class="name" placeholder="Name" name="name" onblur="return validateProductName()"> <p class ="p11" id="p1"></p>
<p class="name-help">Please enter a product name between 1-50 characters.</p>
</div>
My css:
.p11 {
float: right;}
My jQuery:
$(".name").focus(function(){
$(".name-help").slideDown(500);
}).blur(function(){
$(".name-help").slideUp(500);
});
And then my JavaScript:
// Function to validate product name
function validateProductName() {
// if statement for product name
if (document.myForm.name.value.trim().search(pName) == -1) {
alert("Invalid product name. Please note: product name should have 1-50 characters.");
} else {
document.getElementById("p1").innerHTML = "OK";
}
}
So, it prints the OK in between the field on the right side, but I want it right next to the field like I showed in the picture and I can't get this to work! I want it to disappear if I go back to the form and put something wrong...
Thanks guys!
I assume, you have no problem with the jQuery itself, you have a problem of showing it next to input box. So,
Create a <span id='tick'> tag after the input field
And once it passes the validation, use jquery to show the tick
$('#tick').html('whatever you want');
EDIT: You dont have to include the float:left on span
Check out the fiddle link
EDIT:
In this validation function, just show and hide according to the validation results
// Function to validate product name
function validateProductName() {
// if statement for product name
if (document.myForm.name.value.trim().search(pName) == -1) {
document.getElementById("tick").style.display = 'none'; // to hide the OK text if enterd the wrong input
} else {
document.getElementById("tick").innerHTML = "OK"; //NOTE: This is for showing the ok text
document.getElementById("tick").style.display= "block";
}
}
Create a span wherever you want your tick to be displayed and they do this,
$("#btn").click(function() {
if ($("#txtname").val() == "") //can be any check
{
$("#g").attr("style", "display:block;width:20px");
} else {
$("#g").attr("style", "display:none;width:20px;");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="txtname" style="display:inline-block" placeholder="enter name" />
<img id="g" style="width:50px;display:none;" src="http://pixabay.com/static/uploads/photo/2014/04/02/10/19/check-303494_640.png" />
<br/>
<input type="button" id="btn" value="click to submit" />
This should work-
<script src="jq.js"></script>
<div>
<input type="text" class="name" placeholder="Name" name="name" id="input"> <span class ="p11" id="p1"></span>
<p class="name-help">Please enter a product name between 1-50 characters.</p>
</div>
<style>
p11 {
float: right;}
</style>
<script>
$(".name").focus(function(){
$(".name-help").slideDown(500);
}).blur(function(){
$(".name-help").slideUp(500);
validateProductName()
});
</script>
<script>
// Function to validate product name
function validateProductName() {
// if statement for product name
if (document.getElementById("input").value.trim() == "" || document.getElementById("input").value.length > 50 ) {
alert("Invalid product name. Please note: product name should have 1-50 characters.");
document.getElementById("p1").innerHTML = "";
} else {
document.getElementById("p1").innerHTML = "OK";
}
}
</script>

Styling in HTML with CSS while using Javascript

How do I transfer the style code to my external css file? I think using .gamelist won't work because of the <form> or <input> stuff. I know that I can just leave the style in the html file but I like everything to be as neat and organized as possible.
Here's the html code:
<div id="sidebar">
<p class="gamelist">
<FORM>
<input type="image" src="images/mariosadv.jpg" border="2" style="border:2px solid black;max-width:150px;" value="Enter Protected Area" onClick="passWord()">
</FORM>
<FORM>
<input type="image" src="images/mariosadv2.jpg" border="2" style="border:2px solid black;max-width:150px;" value="Enter Protected Area" onClick="passWord()">
</FORM>
</div>
Here's my simple Javascript function:
function passWord() {
var testV = 1;
var pass1 = prompt('Please Enter Your Password',' ');
while (testV < 3) {
if (!pass1)
history.go(-1);
if (pass1.toLowerCase() == "letmein") {
alert('You Got it Right!');
window.open('mariosadv.html');
break;
}
testV+=1;
var pass1 =
prompt('Access Denied - Password Incorrect, Please Try Again.','Password');
}
if (pass1.toLowerCase()!="password" & testV ==3)
history.go(-1);
return " ";
}
Here's the css I tried:
.gamelist img {
display: block;
border: 2px solid black;
width:150px;
margin: 5px 0px 5px 0px;
}
This is what I have with Javascript
http://i.imgur.com/QVc6Dgu.jpg
And this is what I want but without the Javascript
http://i.imgur.com/sNX3Els.jpg
If any additional information is needed please ask before rejecting my question. Thanks.
You'll need to be styling the .gamelist [type=image] instead of .gamelist img, since the img only refers to tags with that name (not to images in general).
EDIT Here's what your HTML should look like:
<div class="gamelist">
<FORM>
<input type="image" src="images/mariosadv.jpg" value="Enter Protected Area" onClick="passWord()">
</FORM>
<FORM>
<input type="image" src="images/mariosadv2.jpg" value="Enter Protected Area" onClick="passWord()">
</FORM>
</div>
As metadept wrote, you'll need to use following CSS selector: input[type='image'].
Be aware that .gamelist input[type='image'] don't select the needed input fields because they haven't the class gamelist.
For a CSS Selector overview use: http://www.w3schools.com/cssref/css_selectors.asp
And please do not use client side authentification!!!

Categories