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.
Related
I'm making two forms with html and javascript, one for "log in" and one for "register". Im using javascript to check that the inputs on the forms are valid. Im running into an issue where the "email" field on the "log in" form is being validated properly, but the "email" field on my "register" form is not, although they are using nearly identical event listeners to validate the inputs.
this is a condensed version of the code that I am using to do this
<html>
<form class="forms" id="login-form" onsubmit="return false" novalidate>
<h1>Log In</h1>
<div class="form-div">
<label for="email">Your Email:</label>
<input type="email" id="email" name="email" required>
<span class="error"></span>
</div>
<button class="wide-buttons" type="submit">Log In</button>
<p onclick="toggleForms()">Need an account? Click here to sign up!</p>
</form>
<form class="forms" id="register-form" onsubmit="return false" novalidate>
<h1>Register</h1>
<div class="form-div">
<label for="email">Your Email:</label>
<input type="email" id="register-email" name="register-email" required>
<span class="error"></span>
</div>
<button class="wide-buttons" type="submit" onclick="validateRegister()">Sign Up</button>
<p onclick="toggleForms()">Already have an account? Click here to log in!</p>
</form>
<script>
const loginForm = document.getElementById("login-form");
const emailError = document.querySelector("#email + span.error");
const registerForm = document.getElementById('register-form');
const regEmailError = document.querySelector("#register-email + span.error");
loginForm.addEventListener("submit", (event) => {
if (!email.validity.valid) {
emailError.textContent = "You must enter a valid email address";
}
});
registerForm.addEventListener("submit", (event) => {
if (!email.validity.valid) {
regEmailError.textContent = "You must enter a valid email address";
}
});
</script>
Im using event listeners for a "submit" event on each form and the one for "loginForm" Is working the way that I intend it to, but the one for "registerForm" is showing my error message when the email is a valid email or anything else is put into the email field. Im stumped by this considering the listeners are practically identical. I don't need to actually submit the form to anything, I'm just trying to learn how some basic form validation works. This code is a snippet of everything else that I have written, but my passwords, checkboxes, etc. are working fine for me. I just need to know how to get the "registerForm" event listener to work the same way that the "loginForm" one is.
edit: Im aware of the onclick="validateRegister()" on the register form- I have removed this in my code and I am still having the issue.
Any help, constructive criticism, or funny jokes are appreciated.
thanks.
It looks like you are trying to check the validity of the email input element on both forms, but you should be checking the validity of the register-email input element on the registerForm event listener.
Change:
if (!email.validity.valid) {
regEmailError.textContent = "You must enter a valid email address";
}
To:
const registerEmail = document.getElementById('register-email');
if (!registerEmail.validity.valid) {
regEmailError.textContent = "You must enter a valid email address";
}
and it should be ok
Edit1: Ofc you can declare registerEmail above event listener
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();
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>
i created a login page, for performing email and password validation. After email and password validation it should perform login validation (it should disable the input fields for some time after 3 login failures) but here the problem is after a login failure the page gets reload and the attempts are not decreasing.
here is my code,
Thanks in advance....
<html>
<head>
<title> Login </title>
<script type='text/javascript'>
var attempt = 3; // Variable to count number of attempts.
// Below function Executes on click of login button.
function validate(){
var username = document.getElementById("jp").value;
var password = document.getElementById("pw").value;
if ( username == "user#gmail.com" && password == "$User123$"){
alert ("Login successfully");
window.location = "success.html"; // Redirecting to other page.
return false;
}
else{
attempt --;// Decrementing by one.
alert("You have left "+attempt+" attempt;");
// Disabling fields after 3 attempts.
if( attempt == 0){
document.getElementById("username").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
}
</script>
</head>
<body>
<div>
<br><h1>Login</h1>
Email:
<form>
<input id="jp" type="text" name="email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$" required placeholder="Enter you Email">
Password:
<input type="password" id="pw" name="psw" pattern="(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{7,15}$" title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters" required>
<br><input type="checkbox" checked="checked"name="remember"> <font>Remember me</font>
<font>Forgot password?</font><br>
<button type="submit" onclick="validate()" ><b>LOGIN<b></button>
</form>
</p>
</div>
</body>
There are a couple of mistakes in your code. The most prominent being, you have to use <form onsubmit="return validate()"> instead of executing the validate function on the click of submit button. I have corrected your complete code and made a pen. Click here to check it.
I've tried, I've researched, and I still can't figure out how to validate this form using jQuery. I've even tried to check out the jQuery API and I had no luck with it. This shouldn't be as hard as it seems. There are a few id's that i'm not using yet because I want to get what I have so far working before I continue. The best I could find for validating emails is just straight up JavaScript. Here's my code.
$(document).ready(function(){
$("#sendForm").click(function(){
var validForm=true; //set valid flag to true, assume form is valid
//validate customer name field. Field is required
if($("#custName").val()) {
$("#custNameError").html(""); //field value is good, remove any error messages
} else {
$("#custNameError").html("Please enter your name.");
validForm = false;
}
//validate customer phone number. Field is required, must be numeric, must be 10 characters
var inPhone = $("#custPhone").val(); //get the input value of the Phone field
$("#custPhoneError").html(""); //set error message back to empty, assume field is valid
if(!inPhone) {
$("#custPhoneError").html("Please enter your phone number.");
validForm = false;
} else {
//if( !$.isNumeric(inPhone) || Math.round(inPhone) != inPhone ) //if the value is NOT numerice OR not an integer. Rounding technique
if( !$.isNumeric(inPhone) || (inPhone % 1 != 0) ) //if the value is NOT numerice OR not an integer. Modulus technique
{
$("#custPhoneError").html("Phone number must be a number.");
validForm = false;
} else {
if(inPhone.length != 10) {
$("#custPhoneError").html("Phone number must have 10 numbers");
validForm = false;
}
}
}
//ALL VALIDATIONS ARE COMPLETE. If all of the fields are valid we can submit the form. Otherwise display the errors
if(validForm) {
//all values are valid, form is good, submit the form
alert("Valid form will be submitted");
//$("#applicationForm").submit(); //SUBMIT the form to the server
} else {
//form has at least one invalid field
//display form and associated error messages
alert("Invalid form. Display form and error messages");
}
}); //end sendform.click
}); //end .ready
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
label {
width:150px;
display:inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2></h2>
<h3>Form Validation Project - Complaint Form</h3>
<form id="form1" name="form1" method="post" action="">
<p>Please enter the following information in order to process your concerns.</p>
<p>
<label for="custName">Name:</label>
<input type="text" name="custName" id="custName" />
<span id="custNameError" class="errorMsg"></span>
</p>
<p>
<label for="custPhone">Phone Number: </label>
<input type="text" name="custPhone" id="custPhone" />
<span id="custPhoneError" class="errorMsg"></span>
</p>
<p>
<label for = "email">Email:</label>
<input type = "text" name = "emailAdd" id = "emailAdd" />
<span id = "emailError" class = "emailError"></span>
</p>
<p>Please Select Product Group:</p>
<p>
<label>
<input type="radio" name="custProducts" value="books" id="custProducts_0" />
Books
</label>
<br />
<label>
<input type="radio" name="custProducts" value="movies" id="custProducts_1" />
Movies
</label>
<br />
<label>
<input type="radio" name="custProducts" value="electronics" id="custProducts_2" />
Consumer Electronics
</label>
<br />
<label>
<input type="radio" name="custProducts" value="computer" id="custProducts_3" />
Computer
</label>
<br />
</p>
<p>Description of problem: (Limit 200 characters)</p>
<p>
<label for="custComplaint"></label>
<textarea name="custComplaint" id="custComplaint" cols="45" rows="5"></textarea>
</p>
<p>
<input type="submit" name="button" id="button" value="File Complaint" />
<input type="reset" name="button2" id="button2" value="Reset" />
</p>
</form>
<p> </p>
$("#button").click(function(e){
e.preventDefault(); // you need to stop the initial event to have a chance to validate
var validForm=true;
// etc...
You can use jquery.validate.js to validate your forms , it will overcome all your manual efforts to create the validation rules also it is providing the various predefined rules like required,email, minlength and maxlength, etc. So, it will be easier for you to achieve what you need very easily.
https://jqueryvalidation.org/
I have a simple jquery form validation and submission package - see if that's of any help - it's easy to install and you can customise quite a few things: https://github.com/sebastiansulinski/ssd-form
Just to get you started, your submit control in the html has id "button", so you should use $('#button').click, not $('#sendForm').click.
Also, if you want to stay on the page (like to do validations, show errors, etc), you have to prevent the form from submitting automatically when the button is clicked. There are lots of ways to do this, but the easiest way is to just change your button type from submit to button. Ie, replace this:
<input type="submit" name="button" id="button" value="File Complaint" />
with this:
<input type="button" name="button" id="button" value="File Complaint" />
------
That should get you started, at least your code will run, you can use console.log to debug, etc. Good luck.
UPDATE
I should add that if you take my advice, the form will never submit on it's own - that is good if some validation fails and you want to stay on the page and give some error feedback to the user.
When you do want the form to submit, you have to make it happen yourself. Again, there are lots of ways to do this, but the simplest one is probably:
$('#form1').submit();