Text obtained with innerHTML dissapear - javascript

I have the following code:
function passVerif() {
if (document.forms['form'].pass.value === "") {
messagePV.innerHTML = ("Password field is empty!")
//alert("Password field is empty!");
return false;
}
return true;
}
function emailVerif() {
if (document.forms['form'].email.value === "") {
messageEV.innerHTML = ("Email field is empty!")
//alert("Email field is empty!");
return false;
}
return true;
}
function validate() {
var email = document.getElementById("input").value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
messageV.innerHTML = ("Please enter a valid e-mail address!")
//alert('Please enter a valid e-mail address!');
return false;
}
}
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br>
<input type="button" name="required" onclick="return passVerif(), emailVerif(), validate()">
</form>
</div>
<div id="messagePV"></div>
<div id="messageEV"></div>
<div id="messageV"></div>
As you can see, input type is submit. Because of that (page is refreshing after click on button) the text I want to show disappears after refresh.
As I read on other posts, the simple change from submit to button will do the dew.
But I am suspecting that I messed up the return false and return true instructions in all of my functions.
Is this correct? If they are in a logical way I can avoid the page refresh and continue to use submit? At least until all conditions are met and the form is good to go.
In other words, can someone help me to put return false and true in such way that the page will refresh only if all conditions are met.
Thanks a lot, I am not even a noob.
Codes are copied from different sources on the internet. I am at the very beginning of coding road. Please have mercy :)

I would change it to one validation function and have a bool that is returned based on if it has errored or not:
// Just have one validation function
function validate() {
var errorMessage = ''; // build up an error message
var email = document.forms['form'].email.value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (email === "") {
errorMessage += "Email field is empty!<br>";
} else if (!emailFilter.test(email)) { // this can be else if
errorMessage += "Please enter a valid e-mail address!<br>";
}
if (document.forms['form'].pass.value === "") {
errorMessage += "Password field is empty!<br>"
}
if (errorMessage === '') {
return true; // return true as no error message
} else {
document.getElementById('error-message').innerHTML = errorMessage; // show error message and return false
return false;
}
}
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br>
<input type="submit" name="required" onclick="return validate();">
</form>
</div>
<div id="error-message">
<!-- CAN HAVE ONE ERROR MESSAGE DIV -->
</div>

I tried with your code and I could find the the messages were not getting updated based on the conditions. So I did few modifications to your code to display the message based on which condition fails.
HTML
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br><br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br><br>
<input type="submit" name="required" value="Submit" onclick="return passVerif(), emailVerif(), validate()">
</form>
</div>
<div id="messagePV"></div>
<div id="messageEV"></div>
<div id="messageV"></div>
JS
function passVerif() {
messagePV.innerHTML = ("")
if(document.forms['form'].pass.value === "") {
messagePV.innerHTML = ("Password field is empty!")
//alert("Password field is empty!");
return false;
}
return true;
}
function emailVerif() {
messageEV.innerHTML = ("")
if(document.forms['form'].email.value === "") {
messageEV.innerHTML = ("Email field is empty!")
//alert("Email field is empty!");
return false;
}
return true;
}
function validate() {
messageV.innerHTML = ("")
var email = document.getElementById("input").value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
messageV.innerHTML = ("Please enter a valid e-mail address!")
//alert('Please enter a valid e-mail address!');
return false;
}
}
By initializing the errormessage filed to empty sting u can maintain the fresh set of error messages.
Jsfiddle: https://jsfiddle.net/85w7qaqx/1/
Hope this helps out.

Related

Not able to match patterns in HTML and JAVASCRIPT

Guys I coded this in html and js. It is just simple three inputs, NAME, EMAIL and PASSWORD. I validated this simple form in javascript but it is not working as expected. I wanted that if I give wrong input to any one of three inputs, it should alert me "Please enter valid credentials." and if I give right input to all of these, It should alert me "Congrats! your form submitted.".
The validation which I gave to NAME field is if length of name is less than 1, it should return false, else true. The validation which I gave to PASSWORD field is same as NAME field and you can see the validation which I gave to all field in my code below. When I give wrong input to only one field, it is still showing me "Congrats! your form submitted."
It is not working as expected!
function ValidateForm(username, email, password)
{
if ((validateusername(username) || validateemail(email) || validatepassword(password))==false)
{
alert("Please Enter Valid Credentials.")
return false
}
else if ((validateusername(username))==true && (validateemail(email))==true && (validatepassword(password))==true)
{
alert("Congrats! your form submitted.")
}
}
function validateemail(email)
{
var x = email.value;
var atposition = x.indexOf("#");
var dotposition = x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length)
{
return false;
}
else
{
return true
}
}
function validateusername(username)
{
if (username.length<1)
{
return false;
}
else
{
return true
}
}
function validatepassword(password)
{
if (password.length<1)
{
return false;
}
else
{
return true
}
}
<form name="myForm">
<input type="text" name="Name" placeholder="Enter Name">
<input type="text" name="EmailAddr" placeholder="Enter Email">
<input type="text" name="Password" placeholder="Enter Password">
<button type="submit" onclick="ValidateForm(document.myForm.Name, document.myForm.EmailAddr, document.myForm.Password)">Submit</button>
</form>
The problem is your if statement condition.
(validateusername(username) || validateemail(email) || validatepassword(password))==false
is the same as
!validateusername(username) && !validateemail(email) && !validatepassword(password)
so you're saying it should only be considered invalid if all 3 validations fail.
This function can be cleaned up and fixed at the same time:
function ValidateForm(username, email, password)
{
if (!validateusername(username) || !validateemail(email) || !validatepassword(password)) {
alert("Please Enter Valid Credentials.")
return false
}
else {
alert("Congrats! your form submitted.")
}
}
That's all you need. If any one of those fails, then the form fails. Otherwise (else) it's fine. You don't need to re-check again.
One improvement you can make is to take as few arguments as necessary without impeding clarity. This function is called "validate form" so I'd expect the form to be the argument, like this:
ValidateForm(document.myForm)
Which is easy to accommodate internally:
function ValidateForm(form)
{
if (!validateusername(form.username) || !validateemail(form.email) || !validatepassword(form.password)) {
alert("Please Enter Valid Credentials.")
return false
}
else {
alert("Congrats! your form submitted.")
}
}
Which requires renaming your form fields to be consistent:
<input type="text" name="name" placeholder="Enter Name">
<input type="text" name="email" placeholder="Enter Email">
<input type="text" name="password" placeholder="Enter Password">
Tip: Try and have one and only one name for your things. Calling it variously Name or name is really counter-productive.
I would avoid inlining events.
Take a look.
document.myForm.addEventListener("submit", validateForm);
function validateForm(event) {
event.preventDefault();
const {
Name: username,
EmailAddr: email,
Password: password,
} = document.myForm;
if (!validateUsername(username) ||
!validateEmail(email) ||
!validatePassword(password)) {
console.log("Please Enter Valid Credentials.")
return;
}
console.log("Congrats! your form submitted.");
}
function validateEmail(emailField) {
const x = emailField.value;
const atposition = x.indexOf("#");
const dotposition = x.lastIndexOf(".");
if (atposition < 1 ||
dotposition < atposition + 2 ||
dotposition + 2 >= x.length) {
return false;
}
return true
}
function validateUsername(username) {
if (username.length < 1) {
return false;
}
return true;
}
function validatePassword(password) {
if (password.length < 1) {
return false;
}
return true;
}
<form name="myForm">
<input type="text" name="Name" placeholder="Enter Name">
<input type="text" name="EmailAddr" placeholder="Enter Email">
<input type="text" name="Password" placeholder="Enter Password">
<button type="submit">Submit</button>
</form>

JavaScript Validation error message is not disappearing after I click submit

The code below validates a form with two fields. When I click the submit button without any data the error messages would show which is working fine but if I input data after and click submit button the error message doesn't disappear.
<script>
function validateForm() {
var valid = true;
var x = document.forms["myForm"]["activityName"].value;
if (x == "" || x == null) {
document.getElementById("activityName").innerHTML = "Please Enter Activity Name";
valid= false;
}
var r = document.forms["myForm"]["reporter"].value;
if (r == "") {
document.getElementById("reporter").innerHTML = "Please Enter Reporter";
valid = false;
}
return valid;
}
</script>
</head>
<body>
<form action="#" method="post" name="myForm" onsubmit=" return validateForm()">
<div>
<label for="myActivityName">*Activity Name:</label>
<input type="text" name="activityName" value="" placeholder="Enter Activity Name" />
<p id="activityName"></p>
</div><br>
<div>
<label for="reporter">*Reporter:</label>
<input type="text" name="reporter" value="" placeholder="Enter Reporter " />
<p id="reporter"></p>
</div><br>
<input type="submit" value="Submit" >
</form>
</body>
The other answer is right, but here is some code to back it up with. Notice that the innerHTML of both activityName and reporter get (re)set back to empty before the validation occurs:
function validateForm() {
var valid = true;
document.getElementById("activityName").innerHTML = "";
document.getElementById("reporter").innerHTML = "";
var x = document.forms["myForm"]["activityName"].value;
if (x == "" || x == null) {
document.getElementById("activityName").innerHTML = "Please Enter Activity Name";
valid= false;
}
var r = document.forms["myForm"]["reporter"].value;
if (r == "") {
document.getElementById("reporter").innerHTML = "Please Enter Reporter";
valid = false;
}
return valid;
}
Your problem is you never "unvalidate" the form a.k.a. remove the previous validation errors. Before you return from validation, if there were no errors, just revert your validation checks. This will ensure it will "clean" your interface if nothing is wrong.

How come my JavaScript isn't working?

I am doing a login page for school. I have written the page, but the JavaScript does not seem to work with the form. I have checked over both the form and the JavaScript multiple times, but I see no mistake. Can anyone help me?
function processInfo() {
var theusername;
var thepassword;
theusername = document.myForm.username.value;
thepassword = document.myForm.password.value;
if (document.myForm.username.value = "") {
alert("Please enter in the username.")
return false;
} else if (document.myForm.password = "") {
alert("Please enter in the password.")
return false;
} else if (document.myForm.username.value != "andrew123") {
document.myForm.txtOutput.value = "Incorrect username or password."
} else if (thepassword != "abc") {
document.myForm.txtOutput.value = "Incorrect username or password."
} else if (theusername == "andrew123"
thepassword == "abc") {
document.myForm.txtOutput.value = "Correct! You have successfully logged in."
}
}
<form name="myForm">
<b>User Name:</b>
<input type="text" name="username" size="36" maxlength="100">
<b>Password:</b>
<input type="text" name="password" size="36" maxlength="100">
<p>
<input type=button value="VERIFY INFORMATION" onClick=processInfo()>
</p>
<textarea name="txtOutput" rows=1 cols=4 0></textarea>
</form>
= is an assignment, you keep using it when you are trying to perform a comparison (which would use == or ===).
Sometimes you try to compare the form control with a string instead of getting its .value.
You forgot to put a boolean AND between the two conditions you have theusername == "andrew123"
thepassword == "abc"
You should learn to use the console in your browser as most of these problems would be highlighted in it or could be with the addition of a little logging.

Javascript validation for email making issues

In my project, I am doing a JS validation for registration purpose. But the validation fails after the email validation. Upto the email validation, it works fine. But after that it is not showing any alerts for rest of validation code.
function signup() {
var signupFullName = $("#signup-full-name");
var signupName = $("#signup-login-name");
var signupEmailAddress = $("#signup-email-address");
var signupPhoneNumber = $("#signup-phone-number");
var signupPassword = $("#signup-password");
var signupConfirmPassword = $("#signup-confirm-password");
var signupAcceptTerms = $("#signup-accept-terms");
if (signupFullName[0].value == "" || signupFullName[0].value == null) {
//alert("Please enter a valid full name.");
alert("Please enter your full name");
signupFullName[0].focus();
return false;
} else if (signupName[0].value == "" || signupName[0].value == null) {
//alert("Please enter a valid login name.");
alert("Please enter your login name.");
signupName[0].focus();
return false;
} else if (signupEmailAddress[0].value == "" || signupEmailAddress[0].value == null) {
//alert("Please enter a valid email address.");
alert("Please enter your email address.");
signupEmailAddress[0].focus();
return false;
}
else if(signupEmailAddress[0].value != "") // problem in this section
{
email=signupEmailAddress[0].value;
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(email))
{
alert("Please enter a valid email address.");
signupEmailAddress[0].focus();
return false;
}
}
else if (signupPhoneNumber[0].value == "" || signupPhoneNumber[0].value == null) {
// alert("Please enter a valid phone number.");\
alert("Please enter your phone number.");
signupPhoneNumber[0].focus();
return false;
} else if (signupPassword[0].value == "" || signupPassword[0].value == null) {
//alert("Please enter a valid password.");
alert("Please enter your password.");
signupPassword[0].focus();
return false;
} else if (signupConfirmPassword[0].value == "" || signupConfirmPassword[0].value == null) {
alert("Please confirm the password.");
signupConfirmPassword[0].focus();
return false;
} else if (signupPassword[0].value != signupConfirmPassword[0].value) {
//alert("Please confirm the password.");
alert("Password mismatch");
signupConfirmPassword[0].focus();
return false;
} else if ($("#signup-accept-terms")[0].checked == false) {
alert("Please accept the terms and conditions.");
return false;
} else {
alert("Done");
return false;
}
}
HTML form code:
<form name="signup-form" id="signup-form" method="post" action="<?php echo $site_path; ?>/register" class="form-1" onsubmit="signup();return false;">
<p class="field">
<a href="<?php echo $root_path; ?>">
<img src="<?php echo $theme_path;?>/images/logo.png"/>
</a>
<h4 style="margin-top:10px;color:#208CCD;">Signup</h4>
<br/>
</p>
<p class="field">
<input type="text" name="signup-full-name" id="signup-full-name" placeholder="Full name">
<i class="icon-user icon-large"></i>
</p>
<p class="field">
<input type="text" name="signup-login-name" id="signup-login-name" placeholder="User name">
<i class="icon-signin icon-large"></i>
</p>
<p class="field">
<input type="text" name="signup-email-address" id="signup-email-address" placeholder="Email address">
<i class="icon-inbox icon-large"></i>
</p>
<p class="field">
<input type="text" name="signup-phone-number" id="signup-phone-number" placeholder="Phone number">
<i class="icon-phone icon-large"></i>
</p>
<p class="field">
<input type="password" name="signup-password" id="signup-password" placeholder="Password">
<i class="icon-lock icon-large"></i>
</p>
<p class="field" style="margin-top:10px;">
<input type="password" name="signup-confirm-password" id="signup-confirm-password" placeholder="Confirm password">
<i class="icon-lock icon-large"></i>
</p>
<p class="field">
<input type="checkbox" name="signup-accept-terms" id="signup-accept-terms" style="margin-top:10px;color:#B3B3B3">
I accept the Terms and Conditions and the Privacy Policies
</input>
</p>
<p class="submit">
<button type="submit" name="submit"><i class="icon-arrow-right icon-large"></i></button>
</p>
</form>
Can anyone help me to solve this? Thanks in advance.
As I see it it's because you use if/else to check validity of the fields.
So the code picks one error at a time - if any. While you should have something like a for-loop across all the fields you want to validate
I mean it picks this
} else if(signupEmailAddress[0].value != "") {
but does not fall into inner check anymore
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(email))
because email is ok now
Your problem is this statement:
else if(signupEmailAddress[0].value != "")
Because the email field contains text, this rule is evaluated as true and so the rest of the else if blocks won't be executed.
I'd consider changing the else if's to be individual if statements so that they won't stop each other.
You have to remove the return false statements inside if condition. Inside validation function, at the end you have to return false if any of the validation fails. Here's an example to do it:
var result = true;
if(condition 1){ // if condition 1 fails, make result = false;
}
if(condition 1){ // if condition 2 fails, make result = false;
}
if(condition 1){ // if condition 3 fails, make result = false;
}
return result; // After all validations, result result
That's it.
Replace your correction place with this code....
else if(signupEmailAddress[0].value != "" && !(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(signupEmailAddress[0].value)) // problem in this section
{
alert("Please enter a valid email address.");
signupEmailAddress[0].focus();
return false;
}

Javascript - Script working only for one element

I have to forms on my webpage, one with name="login" and the other one with name="register" (code below). I use javascript for alerts if the input fields are empty on submitting.
It worked well when I only had one form on the webpage, but the problem starts when I add the other form. It works fine for the first form (login) but when I fill in and submit the second one, it alerts that the fields are empty. (Supposedly, because the login fields are empty).
What's causing this and how do I fix this?
HTML
<form method="post" action="" name="login" onSubmit="return valid();">
<label for="username">Username:</label><br>
<input type="text" name="username"><br>
<label for="password">Password:</label><br>
<input type="password" name="password"><br>
<button type="submit" name="signin">Log inn</button>
</form>
<form method="post" action="index.php" name="register" onSubmit="return valid();">
<label for="username">Username:</label><br>
<input type="text" name="username"><br>
<label for="email">E-mail adress:</label><br>
<input type="text" name="email"><br>
<label for="password">Password:</label><br>
<input type="password" name="password"><br>
<button type="submit" name="signup">Registrer deg</button>
</form>
Script
<script type="text/javascript">
function valid()
{
if(document.login.username.value == "")
{
alert ("Please enter your username.")
document.login.username.focus();
return false;
}
if(document.login.password.value == "")
{
alert ("Please enter your password.")
document.login.password.focus();
return false;
}
}
</script>
<script type="text/javascript">
function valid()
{
if(document.register.username.value == "")
{
alert ("Please enter your username.")
document.register.username.focus();
return false;
}
if(document.register.email.value == "")
{
alert ("Please enter your e-mail adress.")
document.register.email.focus();
return false;
}
if(document.register.password.value == "")
{
alert ("Please enter your password.")
document.register.password.focus();
return false;
}
}
</script>
You are defining two separate functions with the same name, they are overwriting each other. Make two separate functions, validateLogin and validateRegister
<form method="post" action="" name="login" onSubmit="return validateLogin();"> ...
<form method="post" action="" name="login" onSubmit="return validateRegister();">
A slight improvement to your code is for you to pass the form into the handler, so it makes your code shorter and uses fewer globals
<form method="post" action="" name="login" onSubmit="return validateLogin(this);"> ..
function validateLogin(form)
{
if(form.username.value == "")
{
alert ("Please enter your username.")
form.username.focus();
return false;
}
if(form.password.value == "")
{
alert ("Please enter your password.")
form.password.focus();
return false;
}
}
And even better, hookup your handlers through JS instead of HTML
//After the HTML is loaded, and give your form an ID
document.getElementById('loginForm').addEventListener('submit', function(e){
// In IE, the event is global
e = e || window.event;
// "this" points to the form
if(this.username.value == "") {
alert ("Please enter your username.")
this.username.focus();
return false; // or e.preventDefault();
}
if(this.password.value == "") {
alert ("Please enter your password.")
this.password.focus();
return false; // or e.preventDefault();
}
});
And last but not least, you can abstract the work of checking for empty values so your two functions aren't doing the same work.
function createValidator(formId, validations) {
var form = document.getElementById(formId);
form.addEventListener('submit', function(e){
e = e || window.event;
for (var i=0; i < validations.length; i++) {
var elementName = validations[i].elName;
var errorMessage = validations[i].error;
if (form[elementName].value === "") {
alert(errorMessage);
return false; // or e.preventDefault()
}
}
});
}
// And set up both your handlers, remember to give your forms and ID
createValidator('formLogin', [{
elName: 'username',
error: 'Please enter your username'
}, {
elName: 'password',
error: 'Please enter your Password'
}]);
createValidator('formRegister', [{
elName: 'username',
error: 'Please enter your username'
},{
elName: 'email',
error: 'Please enter your email address'
},{
elName: 'password',
error: 'Please enter your Password'
}]);

Categories

Resources