User Registration - Validation & Storing - javascript

I have started to write the validation for user registration. This form is so users can register on the site, however I'm having issues with how to properly write validation for each field.
so far:
<div id="content">
<div class="ic"></div>
<div class="inner">
<div class="container_12">
<div class="wrapper">
<div class="grid_12">
</div>
</div>
<div class="wrapper">
<div class="grid_12">
<h2 class="h-pad1">Open an Account with Us</h2>
<form action="" id="validate" class="form" method="POST">
<fieldset>
<div class="formRow">
<label for="login">Username:</label>
<div class="loginInput"><input type="text" name="username" class="validate[required]" id="username" maxlength="15"/></div>
<div class="clear"></div>
</div>
<div class="formRow">
<label for="pass">Password:</label>
<div class="loginInput"><input type="password" name="password" class="validate[required]" id="pass" /></div>
<div class="clear"></div>
</div>
<div class="formRow">
<label for="pass">Repeat Password:</label>
<div class="loginInput"><input type="password" name="rpassword" class="validate[required]" id="rpass" /></div>
<div class="clear"></div>
</div>
<div class="formRow">
<label for="pass">Email:</label>
<div class="loginInput"><input type="text" name="email" class="validate[required]" id="email" /></div>
<div class="clear"></div>
</div>
What would be the proper code to add? Thank you.

Your most important task is to learn how to use document.getElementById() if your going to be using regular javascript. With that function you can grab the value in the different fields and check what is stored in them.
I would have a highlevel function validateRegistrationForm() that calls functions for validating each field. For example
function validateRegistrationForm(){
if(!validateEmailField()) // Invalid email format
return;
if(!validatePasswordField()) // Invalid password length
return;
if(validateUserNameField()) // invalide characters in email
return;
.
.
etc.
}
function validateEmailField(){
var x=document.getElementById("email").value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
errorPopup("Not a valid e-mail address");
return false;
}
if(email==x) //If the old email is equal to the current then perform no check for uniqueness. On the server side the email portion will be ignored.
return true;
return isEmailUnique(); // return true if the email is unique
}

You can have something like:
function validate()
{
var uName = document.getElementById('username');
if(uName == '' or uName=' ')
{
// do something
}
repeat for other elements.
.
.
.
.
// in the end, you can return true; if all validation condition meet or else return false;
}

Related

JavaScript form validation working unexpectedly and printing undefined

I was trying to write a simple Vanilla JS function which would check if user has left any form fields empty and if that's the case, then alert the user. Unfortunately, it doesn't quite work and I don't know why.
As, you can see it says "undefined can't be left empty".
Here's the JS Code:
var username= document.getElementById("UsernameInput");
var email= document.getElementById("EmailInput");
var pass= document.getElementById("PasswordInput");
var confirmPass= document.getElementById("ConfirmPasswordInput");
var form= document.querySelector(".registration-form");
// Function for checking empty input
function checkEmpty(inputArr){
for(i=0;i<inputArr.length;i++){
if(inputArr[i].value.trim()==='')
var stringified= JSON.stringify(inputArr[i]);
alert(`${stringified} can't be left empty`);
console.log(inputArr[i]);
break;
}
}
form.addEventListener("submit", function(e){
if(checkEmpty([username,email,pass,confirmPass]));
e.preventDefault();
})
So, why is the "stringified" variable undefined? (I'm using JSON.stringify because when I was not doing that it was returning [object object]).
Here's the HTML for the form:
<form action="#" class="registration-form ">
<div class="row ">
<div class="six columns ">
<label for="username">Your username (has to be unique)</label>
<input class="u-full-width" type="text" placeholder="redditStar" id="UsernameInput" name="username">
</div>
</div>
<div class="row">
<div class="six columns">
<label for="email">Your email</label>
<input class="u-full-width" type="email" placeholder="test#emailcom" id="EmailInput" name="email">
</div>
</div>
<div class="row">
<div class="six columns">
<label for="password">Your password</label>
<input class="u-full-width" type="password" placeholder="Enter a strong password" id="PasswordInput" name="password">
</div>
</div>
<div class="row">
<div class="six columns">
<label for="confirm-password">Confirm your Password</label>
<input class="u-full-width" type="password" placeholder="Confirm password.." id="ConfirmPasswordInput" name="passwordConfirm">
</div>
</div>
<input class="button-primary submitRegister" type="submit" value="Submit">
</form>
The problem is your if statement in the for.
for(i=0;i<inputArr.length;i++){
if(inputArr[i].value.trim()==='')
var stringified= JSON.stringify(inputArr[i]);
alert(`${stringified} can't be left empty`);
console.log(inputArr[i]);
break;
}
Following javascript's indentation rules when your if lacks curly braces, if expression is true only the next line is run. If it's false, it skips the next line. So, when that if is false, it jumps to alert(``${stringified} can't be left empty``); which stringified is undefined since it was not defined on the line before.

Email and phone number validation javascript

I want to make validation for my email input text and phone number input text. In the email, I want to put only '#gmail.com' and phone number the user only input number in the form. I already use JavaScript but it doesn't work.
function validation() {
var mailformat = /^\w+([\.-]?\w+)*#gmail.com*(\.\w{2,3})+$/;
var phoneno = /^\d{10}$/;
if (document.getElementById("name").value.length == 0) {
document.getElementById("message").innerHTML = "<em> You did not enter your name </em>";
return false;
}
if (document.getElementById("email").value.match(mailformat) != mailformat) {
document.getElementById("message1").innerHTML = "<em> please enter </em>";
return false;
}
if (document.getElementById("postcode").value.length < 4) {
document.getElementById("message2").innerHTML = "<em> Minimum is 4 Characters for Postcode </em>";
return false;
}
if (document.getElementById("phone").value.length == 0) {
document.getElementById("message3").innerHTML = "<em> You did not enter your phone </em>";
return false;
}
return true;
}
<form class="form-horizontal container" method="POST" action="#" onsubmit="return validation()">
<!-- Name Validation input -->
<div class="form-group">
<label class="control-label col-md-2 label1" style="text-align: left;" for="name">Name:</label>
<div class="col-md-5">
<input type="text" class="form-control" id="name" placeholder="Enter Name" name="name">
<span id="message"></span>
</div>
</div>
<!-- Email Validation input -->
<div class="form-group">
<label class="control-label col-sm-2 label1" style="text-align: left;" for="email">Email:</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="email" placeholder="Enter Email" name="email">
<span id="message1"></span>
</div>
</div>
<!-- Postcode Validation Input -->
<div class="form-group">
<label class="control-label col-sm-2 label1" style="text-align: left;" for="postcode">Postcode:</label>
<div class="col-sm-5">
<input type="text" oninput="this.value=this.value.replace(/[^0-9]/g,'');" class="form-control" id="postcode" placeholder="Enter Postcode" name="postcode">
<span id="message2"></span>
</div>
</div>
<!-- Phone Validation Input -->
<div class="form-group">
<label class="control-label col-sm-2 label1" style="text-align: left;" for="phone">Phone:</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="phone" placeholder="Enter Phone" name="phone">
<span id="message3"></span>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Submit the query</button> <button type="reset" class="btn btn-default button3"> Reset</button>
</div>
</form>
Use regex like this
var mailformat = /^\w+([\.-]?\w+)*[#gmail.com]*(\.\w{2,3})+$/;
var email_val = document.getElementById("email").value;
if(!email_val.match(mailformat)){
document.getElementById("message1").innerHTML = "<em> please enter email dsfsdfa</em>";
return false;
}
You can make it more better, like apply validation for empty field before this too.
Match returns an array if it is matched. So comparing an array to a regular expression is wrong. You can use a truthy check
if(!document.getElementById("email").value.match(mailformat)) {
or use .test() instead.
You could look at this website which shows basic javascript code for validation
https://getcodingkids.com/mission/mission-2/
Where did you get your email validation regex? The pattern /^\w+([\.-]?\w+)*#gmail.com*(\.\w{2,3})+$/ matches (inefficiently) one or more words joined by periods or hyphens, followed by #gmail,followed by any character at all, followed by co, followed by any number of ms including zero, followed by at least one sequence of period plus two or three more letters. So it won't match anything ending in #gmail.com, but will match something ending in #gmail.co.uk or similar. So even if you fix the validation logic in the code, this regex won't match against any email address ending in gmail.com, which it sounds like you want to do..

Error message in contact form

I have created a contact (4 input text) form and I want if user doesn't text in anyone of input a text message will appear above each input.
Contact From:
<form class="form-horizontal" method="post" action="#" name="form" onsubmit="return validation();">
<fieldset>
<div><h2 style="font-family: Myriad Pro;color:#7f8c8c">form</h2></div>
<div class="form-group">
<div class="col-sm-8">
<input id="fname" name="name" type="text" placeholder="Όνομα" class="form-control">
<div id="error1" style="color:#e8645a"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input id="lname" name="surname" type="text" placeholder="Επώνυμο" class="form-control">
<div id="error2" style="color:#e8645a"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-8 ">
<input id="email" name="email" type="email" placeholder="E-mail" class="form-control">
<div id="error3" style="color:#e8645a"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-10 ">
<textarea id="message" name="message" type="text" placeholder="Το σχόλιο σας.." columns="7" rows="7" class="form-control" style="background-color:#e5e6e6;" required=""></textarea>
<div id="error4" style="color:#e8645a"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-3 text-center">
<button type="submit" class="btn btn-primary btn-block" id="label" >SEND</button>
</div>
</div>
</fieldset>
</form>
And the script I use:
function validation(){
if (document.form.name.value == "") {
document.getElementById('error1').innerHTML="*Error Msg1 ";
}else if (document.form.surname.value == "") {
document.getElementById('error2').innerHTML="*Error Msg2 ";
}else if (document.form.email.value == "") {
document.getElementById('error3').innerHTML="*Error Msg3 ";
}else if (document.form.message.value == "") {
document.getElementById('error4').innerHTML="*Error Msg4 ";
}
return false;
}
My issue is that if for example the user doesn't fill his name(error message displayed below the text field) BUT then if he text his name the error message IS still displayed.How can I solve this?
There is an example here: Fiddle
I would suggest that you clear the error message at the start of the validation again:
function validation(){
document.getElementById('error1').innerHTML=""
document.getElementById('error2').innerHTML=""
document.getElementById('error3').innerHTML=""
document.getElementById('error4').innerHTML=""
//Your validation code below:
...
}
This way whenever the input validates, all of the error messages will be cleared and evaluated again.
You might want to consider storing the labels at the start of the function in a field so you have easy access to them later. This should help with readability as well. For example:
function validation(){
var errorMessage1 = document.getElementById('error1');
//Access the label using your new variable:
errorMessage1.innerHTML = "Your value here"
...
On keyup event lets try resetting the error message
document.form.name.addEventListener("keyup", function(){
document.getElementById('error1').innerHTML = '';
});

How to perform client-side form-validation on password

I am doing a simple sign-up page. For the password stuff, I need to check the new password and confirmed password are the same but no idea how
<div class="row">
<!--New Username-->
<div class="large-4 columns form-text">New Username</div>
<div class="large-8 columns">
<div class="input-icon font-awesome"></div><input type="text" class="form-input" name="username" required>
</div>
</div>
<br/>
<div class="row">
<!--New email-->
<div class="large-4 columns form-text">Email</div>
<div class="large-8 columns">
<div class="input-icon font-awesome"></div><input type="email" class="form-input" name="email" pattern="[a-zA-Z]*#[a-zA-Z]*" required>
</div>
</div>
<br/>
<div class="row">
<!--New Passwrord-->
<div class="large-4 columns form-text">New Password</div>
<div class="large-8 columns">
<div class="input-icon font-awesome"></div><input type="password" class="form-input" name="password" required>
</div>
</div>
<br/>
<div class="row">
<!--Reconfirm new password-->
<div class="large-4 columns form-text">Re-enter Password</div>
<div class="large-8 columns">
<div class="input-icon font-awesome"></div><input type="password" class="form-input" name="password-confirm" required>
</div>
</div>
That's quite a bit of code, but I broke out an example on a fiddle.
Simplified HTML:
<form id="passwordForm" action="#" method="POST">
Password:<br>
<input type="password" id="password"><br>
Confirm Password:<br>
<input type="password" id="confirmPassword"><br>
<input type="submit" id="submitButton" value="Check 'Em">
</form>
<div id="responseDiv"></div>
I used jQuery:
$(document).ready(function () {
$("#submitButton").click(function (e) {
e.preventDefault();
var matched,
password = $("#password").val(),
confirm = $("#confirmPassword").val();
matched = (password == confirm) ? true : false;
if(matched) {
//Submit line commented out for example. In production, remove the //
//$("#passwordForm").submit();
//Shows success message and prevents submission. In production, comment out the next 2 lines.
$("#responseDiv").html("Passwords Match");
return false;
}
else {
$("#responseDiv").html("Passwords don't match...");
return false;
}
});
});
Many times new learners will forget the e.preventDefault(); Without it, the form will submit regardless of any validation. Return false if there is something wrong, and the form will not submit.
There is an event listener on the submit button. If it is clicked, or the enter key is pressed will focused in the form, it will run the validation. If everything is fine, it will post the information to the URL in the action attribute of the form tag.
Another important point is to always re-validate on the server side. If a user has their Javascript turned off the form will post the information regardless of what is in your validation script.
with normal javascript, just adapt to your source code:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function pass() {
var pass_1 = document.forms["myForm"].pass_1.value.length;
var pass_2 = document.forms["myForm"].pass_2.value.length;
if (pass_1 != pass_2) {
alert("the pass and repeat pass must be equal");
return false;
}
return true;
}
</script>
</head>
<body>
<form method="post" action="" name="myForm" onSubmit="pass(); return false;">
<input type="password" placeholder="type your pass" name="pass_1">
<input type="password" placeholder="confirm your pass" name="pass_2">
<input type="submit" value="validate">
</form>
</body>
</html>
the same code above but with the redirect: http://jsfiddle.net/m7BrM/
option 2 use a plugin:
http://www.technicalkeeda.com/jquery/password-and-confirm-password-validation-in-jquery

User Registration - Incorrect Logic

I'm having multiple issues with my code. I have wrote a user registration form with validation, however I need help on what I would write for it to be saved in the database and if I'm missing anything. As of right now, it is not working. When I click register, it just refreshes the page.
I appreciate any help, thank you.
<!DOCTYPE html>
<html lang="en">
<head>
<SCRIPT language="JavaScript">
function validateRegistrationForm(){
if(!validateEmailField()) // Invalid email format
return false;
if(!validatePasswordField()) // Invalid password length
return false;
if(validateUserNameField()) // invalide characters in email
return false;
}
function validateEmailField(){
var x=document.getElementById("email").value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
errorPopup("Not a valid e-mail address");
return false;
}
if(email==x) //If the old email is equal to the current then perform no check for uniqueness. On the server side the email portion will be ignored.
return true;
return isEmailUnique(); // return true if the email is unique
}
</script>
</head>
<body class="nobg loginPage">
<header>
</header>
<div id="content">
<div class="ic"></div>
<div class="inner">
<div class="container_12">
<div class="wrapper">
<div class="grid_12">
</div>
</div>
<div class="wrapper">
<div class="grid_12">
<h2 class="h-pad1">Open an Account with Us</h2>
<form action="" id="validate" class="form" method="POST">
<fieldset>
<div class="formRow">
<label for="login">Username:</label>
<div class="loginInput"><input type="text" name="username" class="validate[required]" id="username" maxlength="15"/></div>
<div class="clear"></div>
</div>
<div class="formRow">
<label for="pass">Password:</label>
<div class="loginInput"><input type="password" name="password" class="validate[required]" id="pass" /></div>
<div class="clear"></div>
</div>
<div class="formRow">
<label for="pass">Repeat Password:</label>
<div class="loginInput"><input type="password" name="rpassword" class="validate[required]" id="rpass" /></div>
<div class="clear"></div>
</div>
<div class="formRow">
<label for="pass">Email:</label>
<div class="loginInput"><input type="text" name="email" class="validate[required]" id="email" /></div>
<div class="clear"></div>
</div>
<div class="formRow5">
<script type="text/javascript" src="http://www.google.com/recaptcha/api/challenge?k=6Lfz39kSAAAAABY7fpEs0x1ZzvcFSP-gClbe8XYb"></script>
<noscript>
<iframe src="http://www.google.com/recaptcha/api/noscript?k=6Lfz39kSAAAAABY7fpEs0x1ZzvcFSP-gClbe8XYb" height="300" width="500" frameborder="0"></iframe><br/>
<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
</noscript> </div>
<div class="loginControl">
<input type="submit" value="Register" class="dblueB logMeIn" name="registerBtn"/>
<div class="clear"></div>
</div>
</fieldset>
</form>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<footer>
</div>
</footer>
</body>
</html>
As far as I can tell - you don't have anything linking the submission of the form, to the validation code you've written. Is your validateRegistrationForm() function even being called when you submit the form?
As for your function - you'll want to return true if the form elements are valid, and false if they are not. returning false will cancel submission of the form.
In most cases, you can't use JavaScript to write to a database as JS is client-side code and the database tends to be on a server. In that case you'll need to use a server-side language to do so (like .NET, PHP, Java, etc.). You might be able to get a more detailed answer if you can say what database you want to write to and what server language you are using (if you are using any already).
Before you click the register button, there's a javascript error...
Line 14 column 1: "Uncaught SyntaxError: Unexpected token . "

Categories