Compare two emails in two text fields using Javascript - javascript

I have a form which lets the user to enter the email address twice. i need to validate that the email is like the regex and that the two emails match.
Something is wrong with my code. Please note that i am restricted to use javascript only. Thanks,
this is my javascript
function checkEmail(theForm) {
var re = /^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"+"[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$/i;
if (theForm.EMAIL_1.value != re) {
alert('invalid email address');
return false;
} else if (theForm.EMAIL_1.value != theForm.EMAIL_2.value) {
alert('Those emails don\'t match!');
return false;
} else {
return true;
}
}

Your issue your not actually performing a regex. Your just comparing a regex string to an email.
if(theForm.EMAIL_1.value != re) /// <--- wrong.
{
alert('invalid email address');
return false;
}

On errors, use Event.preventDefault(); to prevent the form submit
Check for email validity only on the first input value
Than check to string equality on both input fields
function checkEmail (event) {
const e1 = this.EMAIL_1.value;
const e2 = this.EMAIL_2.value;
//Email Regex from //stackoverflow.com/a/46181/383904
const re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
const isEmail = re.test( e1 );
const isMatch = e1 === e2;
if( !isEmail ){
event.preventDefault();
alert('Invalid email address');
}
else if ( !isMatch ){
event.preventDefault();
alert("Those emails don't match!");
}
}
document.querySelector("#theForm").addEventListener("submit", formSubmitHandler);
<form id="theForm">
Email address:<br>
<input name="EMAIL_1" type="text"><br>
Confirm Email address:<br>
<input name="EMAIL_2" type="text"><br>
<input type="submit">
</form>
Since you might have more forms where an email is required (Contact form, Login form, Newsletter form, etc etc...) for more modularity you could create a reusable function for validation and than a specific form submit handler separately:
/**
* #param {string} a Email address 1
* #param {string} b Email address 2
* #return {string} Error message
*/
function invalidEmails (a, b) {
a = a.trim();
b = b.trim();
if (!a || !b) return "Missing email";
// Email Regex from stackoverflow.com/a/46181/383904
const re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
const isEmail = re.test(a);
const isMatch = a === b;
if (!isEmail) return "Invalid email";
else if (!isMatch) return "Emails do not match";
}
// Handle your form here
function formSubmitHandler (evt) {
const is_emails_invalid = invalidEmails(this.EMAIL_1.value, this.EMAIL_2.value);
if (is_emails_invalid) {
evt.preventDefault(); // Prevent form submit
alert(is_emails_invalid); // Show error message
}
}
document.querySelector("#theForm").addEventListener("submit", formSubmitHandler);
<form id="theForm">
Email address:<br>
<input name="EMAIL_1" type="text"><br>
Confirm Email address:<br>
<input name="EMAIL_2" type="text"><br>
<input type="submit">
</form>

You cant compare the first value with a regex. You have to use a regexp object. For more information read at
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec

Try this below function to validate your email.
And after the validation, compare the 2nd email.
Please note that regex test method is used in the validateEmail method.
function validateEmail(email) {
var re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return re.test(email);
}

The below should work perfectly!
function validateForm(theForm) {
if (theForm.Email_1.value != theForm.Email_2.value)
{
alert('Emails don\'t match!');
return false;
} else {
return true;
}
}

Related

How can I correctly link my javascript to my html form?

My javascript isn't running when I click submit on my form page.
<form onsubmit="validateReg()">
<p>
//email registration
<input type="text" id="e-mail" placeholder="Email" />
</p><p>
//password registration
<input type="text" id="pswd" placeholder="Password" />
</p>
<br>
<input type="submit" class="submit">
</for
I've tried multiple times linking the Javascript to the Html form and on the page when I click submit it doesn't return any of my error alerts.
//HTML
<form onsubmit="validateReg()">
<p>
<input type="text" id="e-mail" placeholder="Email" />
</p><p>
<input type="text" id="pswd" placeholder="Password" />
</p>
<br>
<input type="submit" class="submit">
</form>
//Javascript
//Main Function
function validateReg(){
var email = document.getElementById('e-mail').value;
var password = document.getElementById('pswd').value;
var emailRGEX = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var emailResult = emailRGEX.test(email);
//validate Email
if(emailResult == false){
alert("Please enter a valid email address");
return false;
}
//validate lower case
var lowerCaseLetters = /[a-z]/g;
if(password.value.match(lowerCaseLetters)) {
return true;
}else{
alert("Password needs a lower case!");
return false;
}
//validate upper case
var upperCaseLetters = /[A-Z]/g;
if(password.value.match(upperCaseLetters)){
return true;
}else{
alert("Password needs an upper case!");
return false;
}
//validate numbers
var numbers = /[0-9]/g;
if(password.value.match(numbers)){
return true;
}else{
alert("Password needs a number!");
return false;
}
//validate special characters
var special = /[!##$%^&*(),.?":{}|<>]/g;
if(password.value.match(special)){
return true;
}else{
alert("Password needs a special character!");
return false;
}
if(password.value.length >=8){
return true;
}else{ alert("Password needs to be at least 8 characters");
return false;
}
}
I expect the code to output errors when a password is incorrectly submitted and when a password and email is correctly submitted so out put thank you.
As Oluwafemi put it you could put an event listener on your 'submit' event instead. I would put the event on the submit button though. That way you can stop it on the click event without having to fire the submit of the form. If you update your code it could help with troubleshooting in the future.
It wouldn't take much to modify your code either.
First, you would need to update your form to look like this:
<form id="form">
<p>
<input type="text" id="e-mail" placeholder="Email" />
</p>
<p>
<input type="text" id="pswd" placeholder="Password" />
</p>
<br />
<input id="submitButton" type="submit" class="submit">
</form>
Then add this below your javascript function like so:
document.querySelector("#submitButton").addEventListener("click", function(event) {
event.preventDefault;
validateReg()
}, false);
What this is doing is stopping the submit of the form and doing the check as expected. You can read more on this on the Mozilla developer site.
You will need to add document.getElementById('form').submit(); to any return statement that was set to true.
I did however, update the code to have the submit become the default functionality and the checks just return false if they fail like this:
//Javascript
//Main Function
function validateReg() {
var email = document.getElementById('e-mail').value;
var password = document.getElementById('pswd').value;
var emailRGEX = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var emailResult = emailRGEX.test(email);
//validate Email
if(emailResult == false){
alert("Please enter a valid email address");
return false;
}
//validate lower case
var lowerCaseLetters = /[a-z]/g;
if(password.match(lowerCaseLetters) == null) {
alert("Password needs a lower case!");
return false;
}
//validate upper case
var upperCaseLetters = /[A-Z]/g;
if(password.match(upperCaseLetters) == null){
alert("Password needs an upper case!");
return false;
}
//validate numbers
var numbers = /[0-9]/g;
if(password.match(numbers) == null){
alert("Password needs a number!");
return false;
}
//validate special characters
var special = /[!##$%^&*(),.?":{}|<>]/g;
if(password.match(special) == null){
alert("Password needs a special character!");
return false;
}
if(password.length < 8){
return false;
}
document.getElementById('form').submit();
}
A better way to do this is to add an event listener to your js file and listen for the 'submit' event. Followed by your function.
Furthermore ensure that your js file is added to your script tag in your HTML file. That should work if your logic is correct.

I want to make a registration form but the script wont work the way i want

To validate the checkpoint the form will have to show an alert if
One of the inputs is empty
The password has less than 8 characters
Doesn't have a valid e-mail adress
The password must be a combination of charatacters , numbers and at least a capital letter
And finally the reset button will reset all the inputs to empty :
//Variable declaration
var username=document.forms["Registration"]["name"];
var e_mail=document.forms["Registration"]["email"];
var password=document.forms["Registration"]["psw1"];
var passwordcheck=document.forms["Registration"]["psw2"];
//add eventListener
username.addEventListener("blur", NameVerify, true);
e_mail.addEventListener("blur", EmailVerify, true);
password.addEventListener("blur", PasswordVerify, true);
passwordcheck.addEventListener("blur", PasswordVerify, true);
// validate the registration
function Validate(){
if (username.value=="")
{
alert("username is required");
username.focus()
return false;
}
if (e_mail.value=="")
{
alert("Email is required");
e_mail.focus()
return false;
}
if (password.value=="")
{
alert("Password is required");
password.focus()
return false;
}
if (passwordcheck.value=="")
{
alert("Re-enter your password");
passwordcheck.focus()
return false;
}
if(password.value != passwordcheck.value){
alert("Password do not match!!")
passwordcheck.focus()
return false;
}
}
//check the username value
function NameVerify(username){
if (username.value !=0) {
document.querySelector.backgroundColor = lightGrey;
return true;
}
}
//check the e_mail
function EmailVerify(e_mail){
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.`\w{2,3})+$/.test(Registration.email.value))`
{
return (true)
}
alert("You have entered an invalid email address!")
e_mail.focus()
return (false)
}
//check the password
function PasswordVerify(password){
var psw = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,20}$/;
if(password.value.match(psw))
{
alert('Correct, try another...')
return true;
}
else
{
alert('Wrong!!')
return false;
}
}
// clear all text inputs when the page is loaded
function clearInp() {
document.getElementsByTagName("input").value = "";
return true;
}
//reset all text fields
function Reset() {
document.querySelector("#Registration").reset();
return true;
}
None of this requires any JavaScript at all.
One of the inputs is empty
<input type="text" required />
The password has less than 8 characters
<input type="password" minlength="8" />
Doesn't have a valid e-mail adress
<input type="email" />
The password must be a combination of charatacters , numbers and at least a capital letter
<input type="password" pattern="(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,}" />
And finally the reset button will reset all the inputs to empty
<input type="reset" value="Reset form" />
Once you've eliminated all JavaScript code from your form, you will find that your form no longer has any JavaScript errors ;)

javascript validation isn't working past validating email input

When I run the following script it will not validate past the email validation. I remove the email validation and it will continue. Any insights to what may be causing the problem?
vEmail = document.getElementById("xEmail").value;
// checks to see if email is formatted correctly
var atpos=vEmail.indexOf("#");
var dotpos=vEmail.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=z.length) {
document.forms['checkout_form'].elements['email'].focus();
alert("Please check your eMAIL ADDRESS. It doesn't appear correct.");
return false;
}
// *** check each field for SHIPPING values ***
vShipTo = document.getElementById("xShipTo").value;
if (vShipTo=="") {
document.forms['checkout_form'].elements['ship_to'].focus();
alert("No SHIP TO NAME entered");
return false;
}
Unless z is defined elsewhere, I think the error stems from z not being defined.
if (atpos<1 || dotpos<atpos+2 || dotpos+2>= (z.length) ) {
This would cause it to fail as if the two conditions are not met, the program will encounter a reference error and stop running. If z is removed, the program continues toward the end.
Edit:
Also, this code is running within a function right?
Correct this(z is undefined here)
if(atpos<1 || dotpos<atpos+2 || dotpos+2 >= z.length) {
to
if(atpos<1 || dotpos<atpos+2 || dotpos+2 >= vEmail.length) {
Here is a working snippet
checkMail();
function checkMail(){
vEmail = document.getElementById("xEmail").value;
// checks to see if email is formatted correctly
var atpos=vEmail.indexOf("#");
var dotpos=vEmail.lastIndexOf(".");
if(atpos<1 || dotpos<atpos+2 || dotpos+2 >= vEmail.length) {
document.forms['checkout_form'].elements['email'].focus();
alert("Please check your eMAIL ADDRESS. It doesn't appear correct.");
return false;
}
//return false;need to set true
}
<body>
<form name="checkout_form" id="checkout_form" action="">
Email:<br>
<input type="text" id="xEmail" name="email" value="#gmail.com">
<br>
<br><br>
<input type="submit" onclick="return checkMail();"value="Submit">
</form>
</body>
Using regular expressions is probably the best way You can use to validate email
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\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,}))$/;
return re.test(String(email).toLowerCase());
}
vEmail = document.getElementById("xEmail").value;
// checks to see if email is formatted correctly
if (!validateEmail(vEmail)) {
document.forms['checkout_form'].elements['email'].focus();
alert("Please check your eMAIL ADDRESS. It doesn't appear correct.");
return false;
}
// *** check each field for SHIPPING values ***
vShipTo = document.getElementById("xShipTo").value;
if (vShipTo=="") {
document.forms['checkout_form'].elements['ship_to'].focus();
alert("No SHIP TO NAME entered");
return false;
}

How can I validate a text box, which should only allow characters A-Z & a-z, not integers nor special characters

How to validate a text box in html, where user will enter his first name, and input do not accept integers & Special Characters?
<input name="txtfname" type="text" maxlength="30" required />
Try this javascript code for validation
function Validate()
{
var val = document.getElementById('your_input_control_id').value;
if (!val.match(/^[a-zA-Z]+$/))
{
alert('Only alphabets are allowed');
return false;
}
return true;
}
You will want to check the username field on both the client and server side.
Javascript:
var username = document.getElementsByName("txtfname")[0].value;
if (username .match(/^[A-Za-z]+$/)) {
// Valid
} else {
// Invalid
}
PHP:
$username = $_POST['txtfname'];
if (preg_match("/^[A-Za-z]+$/", $username ) {
// Valid
} else {
// Invalid
}
In Javascript
var uname = document.form.username;
function validate(){
var letters = /^[A-Za-z]+$/;
if(uname.value.match(letters))
{
return true;
}
else
{
alert('Username must have alphabet characters only');
return false;
}
}
In Html
<form method="post" action="#" onSubmit="return validate();" name="form">
<input type="text" name="username" class="username"/>
<input type="submit" value="submit">
</form>
This is the proper RegEx.
The only punctuations that should be allowed in a name are full stop, apostrophe and hyphen. This RegEx will also work for names like André.
^[\p{L} .'-]+$
var username = document.getElementsById("fname").value;
if (username .match(/^[\p{L} \.'\-]+$/)) {
// Valid username
} else {
// Invalid username
}

Validating Password

I'm trying to validate a password using javascript, It's to make sure that when changing the password, the new password entered is equal to that of the re-entering of the new password (user is asked to enter their new password twice so both have to match) but at the same time, i want to make sure that the new password is at least 6 characters long, I have these functions separately but don't know how to combine them... thanks for help in advance!
This is what i have so far...
This is to make sure the new passwords match:
function validatePassword()
{
var new_password = document.getElementById("new_password").value;
var confirm_new_password = document.getElementById("confirm_new_password").value;
<!-- if they match, go to next page -->
if ( new_password == confirm_new_password)
{
return true;
}
<!-- if they don't match, an error message is displayed -->
else
{
alert("Passwords do not match.");
}
return false;
}
This is for length of password:
function validatePassword()
{
if (document.getElementById("new_password").value.length < "5")
{
<!--If pasword is less than 5 characters long, display error message-->
alert("Please ensure your password is at least 6 characters long.");
return false;
}
return true;
}
How do i combine both of these to form a SINGLE function where the two new passwords are checked so that they match, and also check that they are longer than 6 characters?
To just combine your two functions, this would work:
function validatePassword()
{
var new_password = document.getElementById("new_password").value;
var confirm_new_password = document.getElementById("confirm_new_password").value;
if (new_password.length < 5)
{
<!--If pasword is less than 5 characters long, display error message-->
alert("Please ensure your password is at least 6 characters long.");
return false;
}
else if ( new_password != confirm_new_password)
{
alert("Passwords do not match.");
return false;
}
else
{
return true;
}
}
Although I agree, there are better procedures out there. And please, make sure you're doing server-side validation as well since client-side validation is very easy to skip around.
i m not sure but you can call validatePassword() this function inside
if ( new_password == confirm_new_password)
{
validatePassword();
}
You have two options, either make the two functions a single function, or make them two separate functions and call them both before you submit / process your form.
if (validatePasswordLength() && validatePasswordsMatch()) {
// Continue
}
you have to try this code that is small and working.
if(document.getElementById("new_password").value != document.getElementById("confirm_new_password").value){
alert("Passwords do not match.");
return false;
}
<script>
function validatePassword()
{
var new_password = document.getElementById("new_password").value;
var confirm_new_password = document.getElementById("confirm_new_password").value;
if (document.getElementById("new_password").value.length < "5")
{
alert("Please ensure your password is at least 6 characters long.");
return false;
}
if (new_password == confirm_new_password)
{
alert("Password no match");
return false;
}
return true;
}
</script>
<form action="" onsubmit="return validatePassword()">
<p>New Password: <input type="password" id="new_password" name="new_password" /></p>
<p>Confirm Password: <input type="password" id="confirm_new_password" name="confirm_new_password" /></p>
<p><input type="submit" value="submit" /></p>
</form>

Categories