PHP Code for Email Comparison / Verification - javascript

I am trying to create a function to compare two email fields.
As in :
Email : <input type="text" name="email" id="email" value="<?=$email?>"
required>
Confirm email : <input type="text" name="email2" id="email2"
onblur="confirmEmail()" value="<?=$email2?>" required>
Here is the JavaScript code I inserted into my HTML :
<script type="text/javascript">
function confirmEmail() {
var email = document.getElementById("email").value
var email2 = document.getElementById("email2").value
if (email != email2) {
alert('Email Not Matching!'); }
}
</script>
The code works.
Once the user enters the second email address, localhost displays an alert, saying : "Email not matching"
For extra-measure, I inserted the following into the form's properties : onsubmit="return confirmEmail()
So, if the user ignores the first warning, he gets a second warning when he tries to press the SUBMIT button.
Unfortunately, this is where I am stuck. Because : after the second warning, if the user still does not modify the "confirm email" , the SUBMIT button still works The form gets sent.
How can I modify the code, so that : the error message continues to display until the user changes the email2 correctly??
(I tried using the WHILE function, and the DO....WHILE function. They worked............except that, the error-message kept displaying over and over.........and did not allow me to make the required correction to the email field (haha). I had to close the window completely)

First, give your submit button an ID like this:
<input type="submit" value="Submit" id="mySubmit" disabled="disabled">
And in your if block add:
if (email !== email2) {
alert('Not matching')
document.getElementById("mySubmit").disabled = true;
}else{
document.getElementById("mySubmit").disabled = false;
}

What you could do is:
<script type="text/javascript">
var count=0;
function confirmEmail() {
var email = document.getElementById("email").value
var email2 = document.getElementById("email2").value
function chkEmail(){
if (email != email2 && count==0)
{ alert('Email Not Matching!'); count++ }
else if(email!=email2 && count ==1)
//display warning
}
chkEmail();
}
</script>

I would submit the form with JavaScript.
<form>
Email : <input type="text" name="email" id="email" value="<?=$email?>"
required>
Confirm email : <input type="text" name="email2" id="email2"
onblur="confirmEmail()" value="<?=$email2?>" required>
</form>
<button onclick="formSubmit()">Learn More</button>
Your formSubmit() function would simply pull in the values and submit them after the proper check. This way, regardless of what the user enters, it has to go through your verification before it is submitted.
function formSubmit() {
var email = document.getElementById("email").value;
var email2 = document.getElementById("email2").value;
if (email != email2) {
alert('Email Not Matching!');
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","/Your/Path/To/Your/Form-Processing/?email="+email,true);
xmlhttp.send();
}
The function above will go in your script tags. It checks email and email2 against each and then submits email with GET to the processing page the same way your form would. You can also pass other variables the same way by getting them with document.getElementById('#id').value and then send them through the GET method.

try this bro,
<form name="form" method="post" action="">
Email : <input type="text" name="email" id="email" value="<?=$email?>" required>
Confirm email : <input type="text" name="email2" id="email2" value="<?=$email2?>" required>
<input type="submit" value="submit" onsubmit="return confirmEmail();"/>
</form>
and in java script
<script type="text/javascript">
function confirmEmail() {
var email = document.getElementById("email").value;
var email2 = document.getElementById("email2").value;
if (email != email2)
{ alert('Email Not Matching!'); return false; }
else {
return true;
}
}
</script>

Related

Submit button clearing out form, and not displaying anything

I'm trying to create a fun little registration sheet to practice my validation. When I hit the submit button I have two issues. The first issue is my form keeps clearing every input field the moment I hit submit. I tried to use have my onclick = return false but this did nothing. The next issue I'm having is when I hit submit nothing happens at all. I'm not sure where I have messed up but if someone could point it out to me.
<!-- create a function to validate and pass information along -->
function Validation() {
<!-- declare variables -->
var ifErrors = false;
<!-- create the array to display error messages when cycled through -->
var ErrorMessage = new Array();
var myUserName = document.getElementById("txtUsername").value;
var myPassword = document.getElementById("txtPassword").value;
var myFirstName = document.getElementById("txtFirstName").value;
var myLastName = document.getElementById("txtLastName").value;
var myDateOfBirth = document.getElementById("txtDateOfBirth").value;
var myEmail = document.getElementById("txtEmail").value;
var myPhoneNumber = document.getElementById("txtPhoneNumber").value;
var LettersOnly = /^[a-z]+$/;
var DateOfBirthValidate = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/;
var Dates = new Date();
var DateSupplied = document.getElementById("txtDateOfBirth").value;
var PhoneNumberValidate = /^\([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
<!-- Begin validation -->
//validate for username being blank
if (myUserName = "")
{
ifErrors = true;
ErrorMessage.push('Username is required');
}
//validate for username not being 8 or more characters
if(myUserName.length < 8)
{
ifErrors = true;
ErrorMessage.push('Username must be 8 or more characters');
}
//validate for password being blank
if (myPassword == "")
{
ifErrors = true;
ErrorMessage.push('Password is required');
}
//validate for password not being 8 or more characters
if (myPassword.length < 8)
{
ifErrors = true;
ErrorMessage.push('Password must be 8 or more characters');
}
//validate for first name being blank
if (myFirstName == "")
{
ifErrors = true;
ErrorMessage.push('First name can not be blank');
}
//validate for last name being blank
if (myLastName == "")
{
ifErrors = true;
ErrorMessage.push('Last name can not be blank');
}
//validate for date of birth being blank
if (myDateOfBirth == "")
{
ifErrors = true;
ErrorMessage.push('Last name can not be blank');
}
//validate for date of birth not being formatted like (MM/DD/YYYY)
if (document.getElementById("txtDateOfBirth").value.length > 1)
{
if (! (txtDateOfBirth,valueOf().match(DateOfBirthValidate)));
{
ifErrors = true;
ErrorMessage.push('not a valid date of birth');
}
}
//create a variable to hold date, and see if it's greater than the current date
DateSupplied = new Date(DateSupplied);
if (DateSupplied > Dates)
{
ifErrors = true;
ErrorMessage.push('Date supplied can not be greater than the current date');
}
//va;idate for phone number
if (document.getElementById("txtPhoneNumber").value.length > 1)
{
if (! (txtPhoneNumber.valueOf().match(PhoneNumberValidate)))
{
ifErrors = true;
ErrorMessage.push('Phone number is not valid');
}
}
//successful validation
if (ifErrors == false)
{
ifErrors = true;
alert('Your registration has been processed');
//document.getElementById("RegisterForm").reset();
}
//Display list of messages in list
var DisplayMessage = "";
ErrorMessage.forEach(function (message)
{
DisplayMessage += "<li>" + message + "</li>";
}
);
document.getElementById("Errors").innerHTML = DisplayMessage;
}
<body>
<h3>Registration</h3>
<div>
<ul id="Errors"> </ul>
</div>
<br/>
<form ="RegisterForm">
<label id="lblUsername">Username:</label>
<input type="text" id="txtUsername" />
<br/>
<label id="lblPassword">Password:</label>
<input type="password" id="txtPassword" />
<br/>
<label id="lblFirstName">First Name:</label>
<input type="text" id="txtFirstName" />
<br/>
<label id="lblLastName">Last Name:</label>
<input type="text" id="txtLastName" />
<br/>
<label id="lblDateOfBirth">Date of Birth:</label>
<input type="text" id="txtDateOfBirth" />
<br/>
<label id="lblEmail">Email:</label>
<input type="text" id="txtEmail" />
<br/>
<label id="lblPhoneNumber">Email:</label>
<input type="text" id="txtPhoneNumber" />
<br/>
<input type="submit" value="Submit" onclick="Validation(); return false;" />
<input type="reset" value="reset Form" />
</form>
</body>
return false; does not stop the form from being submitted.
In order to achieve this behavior, you have to call .preventDefault() on the click event of the <input>, or on the submit event of the <form>. Example:
<form>
<input type="submit" onclick="someFn(event)">
</form>
<script>
function someFn(e) {
e.preventDefault();
console.log('form not submitted...');
}
</script>
To prevent all submit events in one go (regardless of which form element initiated it) you can call .preventDefault() on the form's onsubmit handler parameter (which is the submit event):
<form onsubmit="someFn(event)">
<input type="submit">
<button>Submit</button>
</form>
<script>
function someFn(e) {
e.preventDefault();
console.log('form not submitted...');
}
</script>
As a side-note, the submit input does not clear out your form. It sends it.
Because you haven't specified an action attribute on your <form> element, the submission is sent to the current URL.
Which, in practice, reloads the page.
Which, in practice renders a brand new instance of the form, obviously empty.
This is also the reason why "nothing happens at all". The default browser behavior when submitting a form is to actually load the <form>'s action URL (whether it's explicitly specified or not). You're navigating to that URL, along with the form's values. Which means you're not allowing the browser to finish running the code in Validation();. To wait around and see the results of Validation function, you have to prevent the default form submission behavior.
Docs:
<form>: MDN, HTML (Living Standard)
<input type="submit">: MDN, HTML (Living Standard)
Event.preventDefault(): MDN, DOM (Living Standard)

Built a login form script but it's not working using JavaScript

I am trying to build a login.js script that listens for the login form submit event. When I try to run my code, it's not logging in or working properly
I' working with JavaScript, which is requested to use. I built the login form in HTML and have worked on the login function within JavaScript. It can;t be inline JavaScript, it has to be a separate script from HTML.
var count = 2;
function validate() {
var un = document.login.username.value;
var pw = document.login.password.value;
var valid = false;
var usernameArray = ["adrian#tissue.com",
"dduzen1#live.spcollege.edu",
"deannaduzen#gmail.com"
]
var passwordArray = ["welcome1", "w3lc0m3", "ch1c#g0"]
for (var i = 0; i < usernameArray.length; i++) {
if ((un == usernameArray[i]) && (pw == passwordArray[i])) {
valid = true;
break;
}
}
if (valid) {
alert("Login is successful");
window.location = "index.html";
return false;
}
var again = "tries";
if (count == 1) {
again = "try"
}
if (count >= 1) {
alert("Wrong username or password")
count--;
} else {
alert("Incorrect username or password, you are now blocked");
document.login.username.value = "You are now blocked";
document.login.password.value = "You are now blocked";
document.login.username.disabled = true;
document.login.password.disabled = true;
return false;
}
}
<!-- start of login form -->
<div class="login-page">
<div class="form">
<form class="register-form" onsubmit="return validate() ;" method="post">
<input type="text" placeholder="username" />
<input type="text" placeholder="password" />
<input type="text" placeholder="email id" />
<button>Create</button>
<p class="message">Already registered? Login
</p>
</form>
<form class="login-form">
<input type="text" placeholder="username" />
<input type="text" placeholder="password" />
<button>login</button>
<p class="message">Not registered? Register
</p>
</form>
</div>
</div>
It needs to allow the three login information I put into the code to log into the site. When logging in, it blinks as if it's doing something, but isn't going anywhere nor does it show that the person is logged in.
You are not validating correctly with the return sentence, also your onsubmit attribute was in the register form.
Use name attribute on forms
This will help you to identify your forms and inputs easily with JavaScript, otherwise you might have problems identifying which input is which in larger forms.
<form name="login" class="login-form">
<input name="user" type="text" placeholder="username" />
<input name="pass" type="text" placeholder="password" />
<button>login</button>
<p class="message">Not registered? Register
</p>
</form>
With this applied to your login form, you can reference it by doing document.login.
Take advantage over native HTML events in JavaScript
The way you are retrieving the username and password is a lot complex that it should, you can add an event listener in JavaScript and handle everything there:
const loginForm = document.login;
loginForm.addEventListener("submit", validate);
This will call validate every time the form is submitted. Also, it sends the event as a parameter, so you can receive it like this in your function:
function validate(event) {
event.preventDefault(); // Stop form redirection
let user = event.target.user.value,
pass = event.target.pass.value;
// REST OF THE CODE ...
}
This is easier since we added name attributes to the inputs, so we can identify them by user and pass.
Validation
NOTE: I do not recommend validating username:password data directly in the browser, since this is a big vulnerability and must be validated server-side.
You can simplify this validation by binding the username with its password in an object, instead of creating two arrays:
const accounts = {
"adrian#tissue.com": "welcome1",
"dduzen1#live.spcollege.edu": "w3lc0m3",
"deannaduzen#gmail.com": "ch1c#g0"
};
And then, having the inputs value saved in user and pass variables, you can do:
if (accounts[user] == pass) {
//SUCCESSFUL LOGIN
console.log('Correct. Logged in!');
} else {
//WRONG LOGIN CREDENTIALS
attempts--;
validateAttempts();
}
With the purpose of not having a lot of code in sight, you should create another function that its only job is to validate if you should block the user or not.
The result
I should mention that this will only work to validate the user form, if you need to save a session and keep an user logged in, you must use a server-side language.
I leave you a snippet with all of this changes working, see it for yourself:
const accounts = {
"adrian#tissue.com": "welcome1",
"dduzen1#live.spcollege.edu": "w3lc0m3",
"deannaduzen#gmail.com": "ch1c#g0"
};
const loginForm = document.login;
let attempts = 3;
loginForm.addEventListener("submit", validate);
function validate(event) {
event.preventDefault();
let user = event.target.user.value,
pass = event.target.pass.value;
if (accounts[user] == pass) {
//SUCCESSFUL LOGIN
console.log('Correct. Logged in!');
} else {
console.log('Wrong username or password.');
attempts--;
validateAttempts()
}
}
function validateAttempts() {
if (attempts <= 0) {
console.log("You are now blocked");
loginForm.user.value = "You are now blocked";
loginForm.pass.value = "You are now blocked";
loginForm.user.disabled = true;
loginForm.pass.disabled = true;
}
}
<form name="login" class="login-form">
<input name="user" type="text" placeholder="username" />
<input name="pass" type="text" placeholder="password" />
<button>login</button>
<p class="message">Not registered? Register
</p>
</form>

Can't submit form through javascript to php

I have a form in html which I want to run verification in Javascript first before POST ing to PHP. However the link up to the PHP section does not seem to be working despite the fact that I have assigned names to each input tag and specified an action attribute in the form tag.
Here is the HTML code for the form:
<form id="signupform" action="signupform.php" method="post">
<input type="text" name="Email" placeholder="Email Address" class="signupinput" id="email" />
<br />
<input type="password" name="Password" placeholder="Password" class="signupinput" id="passwordone" />
<br />
<input type="password" placeholder="Repeat Password" class="signupinput" id="passwordtwo" />
<br />
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="submit" />
</form>
The button calls the javascript function which I use to verify the values of my form before sending to php:
function verifypass() {
var form = document.getElementById("signupform");
var email = document.getElementById("email").value;
var password1 = document.getElementById("passwordone").value;
var password2 = document.getElementById("passwordtwo").value;
var emailcode = /^(([^<>()\[\]\\.,;:\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 (emailcode.test(email)) {
if (password1.length > 6) {
if (password1 == password2) {
form.submit(); //this statement does not execute
} else {
$("#passwordone").notify("Passwords do not match!", {
position: "right"
})
}
} else {
$("#passwordone").notify("Password is too short!", {
position: "right"
})
}
} else {
$("#email").notify("The email address you have entered is invalid.", {
position: "right"
})
}
}
For some reason, some JavaScript implementations mix up HTML element IDs and code. If you use a different ID for your submit button it will work (id="somethingelse" instead of id="submit"):
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="somethingelse" />
(I think id="submit" has the effect that the submit method is overwritten on the form node, using the button node. I never figured out why, perhaps to allow shortcuts like form.buttonid.value etc. I just avoid using possible method names as IDs.)
I'm not sure why that's not working, but you get around having to call form.submit(); if you use a <input type="submit"/> instead of <input type="button"/> and then use the onsubmit event instead of onclick. That way, IIRC, all you have to do is return true or false.
I think it would be better if you do it real time, for send error when the user leave each input. For example, there is an input, where you set the email address. When the onfocusout event occured in Javascript you can add an eventlistener which is call a checker function to the email input.
There is a quick example for handling form inputs. (Code below)
It is not protect you against the serious attacks, because in a perfect system you have to check on the both side.
Description for the Javascript example:
There is two input email, and password and there is a hidden button which is shown if everything is correct.
The email check and the password check functions are checking the input field values and if it isn't 3 mark length then show error for user.
The showIt funciton get a boolean if it is true it show the button to submit.
The last function is iterate through the fields object where we store the input fields status, and if there is a false it return false else its true. This is the boolean what the showIt function get.
Hope it is understandable.
<style>
#send {
display: none;
}
</style>
<form>
<input type="text" id="email"/>
<input type="password" id="password"/>
<button id="send" type="submit">Send</button>
</form>
<div id="error"></div>
<script>
var fields = {
email: false,
password: false
};
var email = document.getElementById("email");
email.addEventListener("focusout", emailCheck, false);
var password = document.getElementById("password");
password.addEventListener("focusout", passwordCheck, false);
function emailCheck(){
if(email.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Email";
fields.email = false;
} else {
fields.email = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log("asdasd"+show);
showIt(show);
}
function passwordCheck(){
if(password.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Password";
fields.password = false;
} else {
fields.password = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log(show);
showIt(show);
}
function showIt(show) {
if (show) {
document.getElementById("send").style.display = "block";
} else {
document.getElementById("send").style.display = "none";
}
}
function checkFields(){
isFalse = Object.keys(fields).map(function(objectKey, index) {
if (fields[objectKey] === false) {
return false;
}
});
console.log(isFalse);
if (isFalse.indexOf(false) >= 0) {
return false;
}
return true;
}
</script>

JavaScript validation - document.getElementById not working in Bootstrap modal

I am using an onSubmit() function to validate form entries.
The form and validation function work OK,if the form is in a standalone php file or an html file.
But when the form is embedded in a Bootstrap modal the JS validation function throws an error message. [object HTMLInputElement]
I have tried changing document.getElementById('uemail') to document.getElementById('uemail').value as recommended in another answer,
but no value has apparently been passed to the function.
If I remove the onSubmit() attribute then the values are passed correctly to the action script on the server.
This must be common usage. What am I doing wrong?
This is an abbreviated section of my code:
<script>
function formCheck() {
var valid = true;
//alert('in function');
var email = document.getElementById('uemail');
alert('email:' + email);
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email)) {
alert('Please provide a valid email address');
email.focus;
valid = false;
}
return valid;
}
</script>
<form id="regform" action="action.php" method="post" onSubmit="return formCheck()">
Email: <input type="text" name="uemail" id="uemail" size="50" value="" required><span id ="ast">*</span><br>
<input type="submit" name="Submit" value="Register" />
</form>
EDIT: looks like you can't do document.getElementById, you can do this instead:
function formCheck(formEl) {
//...
var email = formEl.getElementsByTagName("input")[0].value;
// this will get the first input-element in your form
and
onsubmit="return formCheck(this)"
Mistake: The variable email you are testing is a HTMLElement, not a string:
Solution: set email to the value of the HTMLInputElement:
var email = document.getElementById('uemail').value;
also email.focus; is not doing anything, use email.focus();
Demo:
function formCheck() {
var valid = true;
//alert('in function');
var email = document.getElementById('uemail').value;
alert('email:' + email);
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email)) {
alert('Please provide a valid email address');
email.focus;
valid = false;
}
return valid;
}
<form id="regform" action="action.php" method="post" onsubmit="alert(formCheck())">
Email:
<input type="text" name="uemail" id="uemail" size="50" value="" required><span id="ast">*</span>
<br>
<input type="submit" name="Submit" value="Register" />
</form>

HTML form being reloaded and java script message not being displayed

I am a new to Javascript programming. I have developed the below script and encountering the below issues. Request the expert to help to resolve the issues.
Issues are
when both username and password are filled (username not equal to password) the javascript message displays and the form automatically reloads removing the message.
when username or password is left empty, the message being displayed is "Invalid username or password". The correct javascript message is not being displayed.
when both the fields are not filled the script executes successfully and "Welcome" is printed. If condition in javascript not being executed to display the correct message. Also have used "required" attribute to display the error "this field is required" but still "welcome' is being printed.
<!DOCTYPE html>
<html>
<head>
<script>
function verify() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if ((typeof username) == undefined) {
document.getElementById("message").innerHTML = "Username Required.";
}
if ((typeof password) == undefined) {
document.getElementById("message").innerHTML = "password Required.";
}
if (username == password) {
document.write("Welcome");
}
else {
document.getElementById("message").innerHTML = "Invalid Username or password";
}
}
</script>
</head>
<body>
<h1 style="text-align:center">Welcome to MEPC World!!</h1>
<br>
<form style="margin:auto;max-width:60%" >
<fieldset style="border:groove;border-width:5px;border-color:lightgrey;text-align:center">
<legend><b>Login</b></legend>
<p id="message" style="color:red;text-align:left"></p>
<br>
Username :
<input id="username" type="text" placeholder="username (e.g. XYZ)" autocomplete="off" required="required"> </input>
<br>
<br>
Password :
<input id="password" type="password" placeholder="password" required="required"> </input>
<br><br>
<input type="submit" value="Submit" onclick="verify()">
</fieldset>
</form>
<p><b>Note:</b> Username and password are case-sensitive.</p>
</body>
</html>
This is how you should be doing it. Or the message gets overridden because you have multiple if statements instead of an if/elseif/else which will only allow one to be true.
function verify() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username === undefined || username === '') {
document.getElementById("message").innerHTML = "Username Required.";
}
else if (password == undefined || password === '') {
document.getElementById("message").innerHTML = "password Required.";
}
// This doesn't make sense at all fyi
else if (username === password) {
document.write("Welcome");
}
else {
document.getElementById("message").innerHTML = "Invalid Username or password";
}
}
To prevent the form from submitting you have to do this:
<input type="submit" value="Submit" onclick="return verify()">

Categories