Validate user inputs before submit form - javascript

I have this code to validate inputs:
<script>
function validate()
{
var firstName = document.form.fullname.value;
var lastName = document.form.fullname.value;
var email = document.form.email.value;
var password = document.form.password.value;
var conpassword = document.form.conpassword.value;
if (firstName == null || firstName == "")
{
alert("Firstname can't be blank");
return false;
} else if (lastName == null || lastName == "")
{
alert("Lastname can't be blank");
return false;
} else if (email == null || email == "")
{
alert("Email can't be blank");
return false;
} else if (password.length < 6)
{
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
And this is my form:
<form name="form" action="<%=request.getContextPath()%>/register" method="post">
<div class="container">
<div class="left">
<div class="header">
<h2 class="animation a1">Register now</h2>
<h4 class="animation a2">Enter information in field and create account!</h4>
</div>
<div class="form">
<input type="text" name="firstName" class="form-field animation a3" placeholder="Name...">
<input type="text" name="lastName" class="form-field animation a3" placeholder="Last name...">
<input type="email" name="email" class="form-field animation a3" placeholder="Email adress...">
<input type="password" name="password" class="form-field animation a4" placeholder="Password">
<button class="animation a6" value="Submit" type="submit">REGISTER</button>
</div>
</div>
<div class="right"></div>
</div>
</form>
How to implement that function to my form? Because now when I click submit, in my database an empty user is added. I want to add that it throws out an error in each field if it is not validly filled in

You can get the validate function to execute by adding an 'onsubmit' to your form html tag ( see here w3 Schools for executing a function on submit: onsubmit in forms)
As for the errors, when executing the code, the function cannot read a property 'value' of undefined. So what is happening is that you are telling the validate function to get parts out of the form out that it cannot find (fullname and conpassword are not defined).
Take a look at your form's name tags for fields and then reference those names in the validate function. So when declaring firstName instead of document.form.fullname.value try document.form.firstName.value referring in the form. Do this for first and last name using their names in the form, and also get rid of (or comment out) the conpassword variable.

This validation could be done without javascript function. Use the "required" tag for the inputs which are mandatory.
For example :
<input type="text" name="firstName" class="form-field animation a3" placeholder="Name..." required>
In case of password you may use the pattern attribute.
If you need to use javascript in particular, then go for onclick in the button tag.
<button class="animation a6" onclick="validate()">REGISTER</button>
and include the form submit in the javascript function -
document.form.submit();

Related

Why does my submit button refuse to submit?

So I made a code that reads the name and password form in html. In java script I made code to ensure that the name and password fields are filled in. It also records that if the password value is less than or equal to 6 a message would display "Password must be longer than 6 characters" and if the password value is greater than or equal to 15 a message would display "Password must be shorter than 15 characters" (extra: for whatever reason when I put a 6 character password it would display that message despite the operator I included same goes for the latter).
Here's the HTML Code Followed by the javascript:
<!--Error container-->
<div id="error"></div>
<!--Form-->
<form id="form" action="/" method="GET">
<fieldset>
<!--Legend-->
<legend>Form: </legend>
<!--Name-->
<label for="name">Name:</label>
<input type="text" name="Name" id="name">
<br><br>
<!--Password-->
<label>Password: </label>
<input type="password" name="password" id="password">
<br><br>
<!--Submit and Reset Button-->
<input type="submit" Value="Submit">
<input type="reset" Value="Reset">
</fieldset>
</form>
<!--form-->
[Filler text: I thought I made the question as simplistic and easy to follow as it needs to be]
Here's the javascript portion.
The first four lines gets the id from the html code dropped from above and then the magic happens from there.
const name = document.getElementById('name')
const password = document.getElementById('password')
const form = document.getElementById('form')
const errorElement = document.getElementById('error')
form.addEventListener('submit', (e) =>{
let messages = []
if(name.value === '' || name.value == null){
messages.push("Name is required")
}
if(password.value.length <= 6){
messages.push("Password must be longer than 6 characters")
}
if(password.value.length >= 15){
messages.push("Password must be shorter than 15 characters")
}
if(messages.length > 0){
e.preventDefault()
errorElement.innerText = messages.join(', ')
}
e.preventDefault()
})
Please stick to Javascript and html
And thank you for using your time to read and lend a hand.
Your form won't submit because you're actively preventing it from doing so using e.preventDefault()
I would either just remove that or trigger a submit action via JavaScript if no errors occur:
if (!messages) //the variable messages is empty, so there are no errors
form.submit() //submit the form
This might also help you:
How can I submit a form using JavaScript?
Just a few minor things:
<= 6 is what's causing it to still show the error message when it's exactly 6 characters. Updating it to < 6 will only show the message when the password is less than 6 characters (as opposed to less than or equal to)
The e.preventDefault() is still being called, even outside of the error check
The messages array is never reset, so even once the user has fixed all errors, the form is still being prevented from submitting
Here's an updated version:
const name = document.getElementById('name')
const password = document.getElementById('password')
const form = document.getElementById('form')
const errorElement = document.getElementById('error')
form.addEventListener('submit', (e) =>{
let isValid = true;
let messages = []
if(name.value === '' || name.value == null){
messages.push("Name is required");
isValid = false;
} else if(password.value.length < 6){
messages.push("Password must be longer than 6 characters");
isValid = false;
} else if (password.value.length >= 15){
messages.push("Password must be shorter than 15 characters");
isValid = false;
}
if(!isValid){
e.preventDefault()
errorElement.innerText = messages.join(', ')
}
})
<!--Error container-->
<div id="error"></div>
<!--Form-->
<form id="form" action="/" method="GET">
<fieldset>
<!--Legend-->
<legend>Form: </legend>
<!--Name-->
<label for="name">Name:</label>
<input type="text" name="Name" id="name">
<br><br>
<!--Password-->
<label>Password: </label>
<input type="password" name="password" id="password">
<br><br>
<!--Submit and Reset Button-->
<input type="submit" Value="Submit">
<input type="reset" Value="Reset">
</fieldset>
</form>
<!--form-->
Side note: In real life, you never want to restrict the length of the users password. Let them make it as strong as they like. You're going to hash it anyway, so length and special characters won't be an issue for storage.

validate input with js

this is my register.php code
<form id="register_form" onsubmit="return false" autocomplete="off" >
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" class="form-control" id="username" placeholder="enter username">
<small id="u_error" class="form-text text-muted"></small>
</div>
<button type="submit" name="user_register" class="btn btn-primary"><span class="fas fa-user"></span> Register</button>
this is my js
$(document).ready(function(){
// alert("hello friends");
$("register_form").on("submit",function() {
var status = false ;
var name = $("#username");
if (name.val() == "" || name.length < 6 ) {
name.addClass("border-danger");
$("#u_error").html("<span class='text danger'> name more that 6 char</span>");
status = false;
}else {
name.addClass("border-danger");
$("#u_error").html("<span class='test danger'> please enter name</span>");
status = true;
}
})
})
here i try username field less than 6 or empty through js i validate but its not working may i know why?
There are so many changes into you code.
1.html - add submit button with </form>
2.js - your event is on '#register_form' instead of 'register_form'
3.js - To prevent on submit you have to return true or false..in you case return status; after if-else
4.js - use name.val().length instead of name.length
Nothing happens because you are submitting the form, causing a redirect to another page or to the same page in order to do things with the backend on the server.
In order to prevent the form from submitting, do the following:
$("register_form").on("submit",function(event) {
event.preventDefault();
//... rest of your code
The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.
Event.preventDefault()
Besides, you are now checking if the value of name is empty, or the count of elements with id username is less than 6. To check the length of the value of name, do the following:
name.val().length < 6
count length on value not on object, change name.length to name.val().length
if (name.val() == "" || name.val().length < 6 ) {
Instead I suggest change here
var name = $("#username").val();
and check like below, there is no need to check for empty, only name.length < 6 is enough
if (name.length < 6 ) {
$(document).ready(function(){
$('#frm').submit(function(){
if(!$('#name').val()){
alert('Please enter your name');
}
else if(!$('#age').val()){
alert('Please enter your age');
}
else if(!$('#mobile').val()){
alert('Please enter your mobile');
}
else if(!$('#email').val()){
alert('Please enter your email');
}
});
});
<html>
<head>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<form id="frm">
<input type="text" name="name" id="name" placeholder="Name..."><br><br>
<input type="number" name="age" id="age" placeholder="Age..."><br><br>
<input type="number" name="mobile" id="mobile" placeholder="Mobile..."><br><br>
<input type="email" name="email" id="email" placeholder="Email..."><br><br>
<input type="submit" name="submit" id="submit">
</form>
</body>
</html>

Form Validation through Jquery: This not working with Jquery Latest version of CDN (Content Delivery Network)?

This not working with Jquery Latest version of CDN (Content Delivery Network):
Validating HTML forms is a very important aspect during form submission. jQuery helps in validating forms at client side. The following steps are required to validate a form.
Step 1: Create a Simple HTML Form
To create the form use the following code.
<h1>Fill out your information</h1>
<form id="regForm" method="post">
<input type="text" name="fullname" id="fullname" placeholder="Your Full Name"/>
<input type="text" name="email" id="email" placeholder="Email ID"/>
<input type="text" name="mobileno" id="mobileno" id="mobileno" placeholder="Mobile Number" maxlength="10"/>
<input type="text" name="address" id="address" placeholder="Address"/>
<input type="password" name="password" id="password" value="" placeholder="Password"/>
<input type="password" name="repassword" id="repassword" value="" placeholder="RetypePassword"/>
<button name="submit" type="button" id="btnvalidate">Click to Submit</button>
</form>
This is the form view of the above code
Step 2: Include the Latest jQuery Library
The latest jquery library can be downloaded from https://jquery.com/. Add the latest library to the head section of HTML page.
Step 3: Add a Function to Validate Form
Add the jquery function within the "" tags in the HTML form. Use the following code to validate the form.
<script type="text/javascript">
//Find the values added in form using the id of each fields. The ".val()" function finds the value added in the form fields.
var fullname = $('#fullname').val();
var address = $('#address').val();
var mobileno = $('#mobileno').val();
var email = $('#email').val();
var indexat = email.indexOf("#"); //Index of "#" in the email field
var indexdot = email.indexOf("."); //Index of "." in the email field
var password = $('#password').val();
var repassword = $('#repassword').val();
//Function will execute when the button "Click to Submit" is clicked.
$('#btnvalidate').click(function() {
//Blank field validation of fullname, mobile no and address. The function will generate an alert message if "fullname" or "mobile no" or "address" field is blank
if(fullname == '')
{
alert('Please enter your Full Name');
$('#fullname').focus(); //The focus function will move the cursor to "fullname" field
}
else if(address == '')
{
alert('Please enter your Address');
$('#address').focus();
}
else if(mobileno == '')
{
alert('Please enter your Mobile Number');
$('#address').focus();
}
//Validation of valid email address. The function will generate an alert message if "email" field is blank or incorrect
else if(indexat < 1 || (indexdot-indexat) < 2)
{
alert('Please enter a valid Email Id');
$('#email').focus();
}
//Validation of password. The function will generate an alert message if "password" field is not same as "retype password".
else if(password == '' && password != repassword)
{
alert('Password and Retype password donot match');
$('#repassword').focus();
}
});
</script>
you have to get all the text field values inside your click event.

Trying to verify passwords are matching using html and javascript

I have a form that is supposed to register a user and I have two inputs for passwords that are supposed to be the same. I use html for the form and javascript to check if both inputs are matching. The code I'm using doesn't work though because even if the passwords are different, the user data is still sent to my console when the form shouldn't be able to submit in the first place. These are portions of my html file.
<form id="registration-info" method="POST" action="/registration" onsubmit="return validatePassword();">
....
<div class="mb-3">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" id="password" required>
<div class="invalid-feedback">
Please enter a password.
</div>
</div>
<div class="mb-3">
<label for="repeat_password">Repeat Password</label>
<input type="password" class="form-control" name="repeat_password" id="repeat_password"required>
<script language='javascript' type='text/javascript'>
var password = document.getElementById("password")
, repeat_password = document.getElementById("repeat_password");
function validatePassword(){
if(password.value != repeat_password.value) {
document.repeat_password.setCustomValidity("Passwords Don't Match");
} else {
document.repeat_password.setCustomValidity('');
}
}
</script>
</div>
You have a few mistakes there you'll need to fix up.
Use a JavaScript event listener and remove document..
form = document.getElementById("registration-info");
form.onclick = function() {
var password = document.getElementById("password");
var repeat_password = document.getElementById("repeat_password");
if(password.value != repeat_password.value) {
repeat_password.setCustomValidity("Passwords Don't Match");
} else {
document.repeat_password.setCustomValidity('');
}
}
You do not need to use document. when references variables you have set. Using a JavaScript event listener helps you write clean code, that separates UI and logic.

How to append some text to text box

This JavaScript checks whether the name-text box is empty or not.
If empty then the same line should have "Name is required" appended.
function checkFields(){
var name = document.forms["contact-form"]["name"].value;
if(name == ""){
}
<!--- This is the html code for text box for name and submit button to call checkFields() method -->
<div class="required-fields">
<label>My Name:</label>
<input type="text" name="name"/>
</div>
<input type="button" onclick="checkFields()" value="Send Message"/>
Well I think you just need placeholder html attribute, google it.
And, the method you chose is more likely not necessary in the first place, still check this updated fiddle out,
function checkFields(){
var name = document.forms["contact-form"]["name"].value;
console.log(name);
if(name == ""){
document.getElementsByClassName('error-text')[0].innerHTML='Name field required'
}
else{
document.getElementsByClassName('error-text')[0].innerHTML='';
}
}
Try with placeHolder : or use with input required method . if you need with append some error see the below snippet:
Snippet:
function checkFields(){
var name = document.forms["contact-form"]["name"].value;
if(name =="" ){
document.getElementById("input").placeholder = "**Name required**";
document.getElementById("error").innerHTML ="**Name required**";
}
}
<!--- This is the html code for text box for name and submit button to call checkFields() method -->
<form name="contact-form">
<div class="required-fields">
<label>My Name:</label>
<input type="text" name="name" id="input" >
<p id="error" style="color:red"></p>
</div>
<input type="button" onclick="checkFields()" value="Send Message"/>
</form>

Categories

Resources