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.
Related
So I am trying to add validation to a form. Initially, for the button, I had the type as submit, but when I would click on the button the error message for an empty name input would display briefly. I did some research and saw that in order to get the error message to display longer, I needed to change the type to button, which I did. Now, no error messages are showing. I checked the console and there are no errors displaying. Can someone tell me why this is happening and how to fix it?
function printError(elemId, message) {
document.getElementById(elemId).innerHTML = message;
}
function validateForm() {
var name = document.regForm.FullName.value;
var nameError = true;
if (name == "") {
printError("nameError", "Please enter your name")
}
};
.error {
color: red;
font-size: 90%;
}
<div class="container">
<form name="regForm" class="form" onsubmit="return validateForm()">
<fieldset>
<div class="row">
<label>Full Name</label></br>
<input name="FullName" type="text" placeholder="John Doe" id="FullName" />
<div class="error" id="nameError"></div>
</div>
<div class="row">
<label>Email</label></br>
<input name="email" type="email" placeholder="johndoe#email.com" id="Email" />
<div class="error" id="emailError"></div>
</div>
<div class="row">
<label>Phone Number</label></br>
<input name="phone" type="tel" placeholder="(123) 456-7890" id="PhoneNumber" />
</div>
<div class="row">
<label>Password</label></br>
<input name="Password" id="Password" type="Password" placeholder="Password" onchange='passConfirm();' />
</div>
<div class="row">
<label>Confirm Password</label></br>
<input name="ConfirmPassword" id="ConfirmPassword" type="Password" placeholder="Confirm Password" onchange='passConfirm();' />
</div>
<span id="Message"></span>
<button type="button" value="submit">Sign Me Up!</button>
</fieldset>
</form>
</div>
When the button type is submit the form gets submitted automatically and the function called validation is executed. But when you change the type to button the function will not be called. You have to add click event listener to the sign me up button to call the validate function.
jsFiddle
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..
The method validateRegistrationForm is not being called, I have tested this by placing an alert inside and can't figure out why this is the case.
There is other JavaScript to validate other things though I have removed that until this issue is resolved.
The JavaScript itself is being linked to the HTML via script tags inside of the body. I put an alert at the top of the JS to make sure the link is working and it is.
HTML:
<form name="registrationForm" id="registrationForm" action="AddUserDetails">
<div class="form-group">
<label for="firstName">First Name</label>
<span id="firstNameError">*</span>
<input type="text" class="form-control" id="firstName">
</div>
<div class="form-group">
<label for="lastName">Second Name</label>
<span id="lastNameError">*</span>
<input type="text" class="form-control" id="lastName">
</div>
<div class="form-group">
<label for="phoneNumber">Phone Number</label>
<span id="phoneNumberError">*</span>
<input type="text" class="form-control" id="phoneNumber">
</div>
<div class="form-group">
<label for="eMail">E-Mail</label>
<span id="eMailError">*</span>
<input type="text" class="form-control" id="eMail">
</div>
<div class="form-group">
<label for="eMailConfirmation">Confirm E-Mail</label>
<span id="eMailConfirmationError">*</span>
<input type="text" class="form-control" id="eMailConfirmation">
</div>
<div class="form-group">
<label for="password">Password</label>
<span id="passwordError">*</span>
<input type="password" class="form-control" id="password">
</div>
</form>
<div class="text-center">
<input type="button" id="submitRegistationForm" value="Submit">
</div>
JavaScript:
var $ = function (id) {
return document.getElementById(id);
}
var validateRegistrationForm = function () {
alert("");
var isValid = true;
//First Name Validation
if ($("firstName").value == "") {
$("firstNameError").firstChild.nodeValue = "This Text Box Cannot Be Blank";
isValid = false;
} else {
$("firstNameError").firstChild.nodeValue = "";
}
//Second Name Validation
if ($("lastName").value == "") {
$("lastNameError").firstChild.nodeValue = "This Text Box Cannot Be Blank";
isValid = false;
} else {
$("lastNameError").firstChild.nodeValue = "";
}
if (isValid) {
$("registrationForm").submit();
}
}
window.onload = function () {
$("submitRegistationForm").onclick = validateRegistrationForm;
}
Redefining $ seems like an awful idea, especially if this is code shared amongst other developers. In either case, why even wait for window.onload? You could just declare your click handler outside of it. Working jsfiddle:
$("submitRegistationForm").onclick = validateRegistrationForm;
https://jsfiddle.net/ou3gLLqe/
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 = '';
});
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