For Javascript in HTML Form Still Submits Despite Breaking Requirements - javascript

So essentially my problem is that I am trying to make a form where certain rules need to be met, like the password should have an uppercase and you need to confirm your password, but despite failing the validation the form will still submit. The only validation that works is the default requirement that the text box needs to have something written in it. How would I go about making it so the validation actually stops the form from going through.
The code I currently have works in that it will return true/false depending on if it passes, its just that even if it does not pass the form will still go through. I know I probably need a event.preventDefault() somehwhere but I don't know where.
<form class="w3-container w3-margin" name="login" action="loginAction.jsp">
<h1>Create a Username and Password</h1>
<!-- These divs are the text fields for information the user needs to give the website -->
<div class="w3-section">
<label>Username</label>
<input class="w3-input w3-border" type="text" placeholder="Name" name="username" size="20" required>
</div>
<div class="w3-section">
<label>Email</label>
<input class="w3-input w3-border" type="text" placeholder="Email" name="email" required>
</div>
<!-- For the password the method validPassword() is used which checks if the password has an uppercase -->
<div class="w3-section">
<label>Password (Must have at least one upper case)</label>
<input class="w3-input w3-border" type="text" placeholder="Password" name="password" onInput="validPassword()" size="15" required>
</div>
<!-- For confirm password the method matchingPasswords() is used which checks if the two typed passwords are the same -->
<div class="w3-section">
<label>Confirm Password</label>
<input class="w3-input w3-border" type="text" placeholder="Confirm Password" name="cpassword" onInput="matchingPasswords()" size="15" required>
</div>
<!--These are submit and reset buttons -->
<div class="w3-section">
<input class="w3-button topbotColor" type="submit" value="Button" />
<input class="w3-button topbotColor" type="reset" value="Reset" />
</div>
</form>
This is the javascript code.
//function validPassword is meant to check if the password has a uppercase letter
function validPassword() {
//var password stores the password element from the text box
var password = document.getElementsByName("password");
//var ucletters is the set of all capital letters
var ucletters = /^(?=.*[A-Z]).+$/;
//If there is at least one uppercase in the password text
if(ucletters.test(password[0].value)){
//Pass validity and return true
document.getElementsByName("password").setCustomValidity("");
return true;
}
else {
//else the password does not have an uppercase
document.getElementByName.setCustomValidity("This password does not fit criteria");
return false;
}
}
//matchingPasswords is meant to check if two passwords were the same
function matchingPasswords() {
//password stores the text in the password text box
var password = document.getElementsByName("password");
//cpassword stores the text in the confirm password text box
var cpassword = document.getElementsByName("cpassword");
//If the string in password does not match the string in confirm password
if (password[0].value !== cpassword[0].value) {
//it fails validity and should return false
document.getElementsByName("cpassword").setCustomValidity("Emails do not match");
return false;
}
else {
//else it passes and should be true
document.getElementsByName("cpassword").setCustomValidity("");
return true;
}
}
/*function completeForm() {
if (validPassword() !== true && matchingPasswords() !== true){
event.preventDefault();
}
}*/

1.) Remove the forms action value
2.) Add Event Listeners for your code to run(I don't see how any functions are running)
document.getElementById("your_submit_button").addEventListener('click', function_you_want_to_run);
3.) Use this code to redirect the client to your form action
window.location.url="/link.jsp";

Related

pattern() function and onkeyup() function not working together

i am trying to let the screen show that the password inserted should be in a certain regex with pattern when typing in the fields but when i used onkeyup() to check if both passwords are matching the part with the onkeyup works but
the pattern info box doesnt show up anymore
so i was hoping to know why its not working ,if both functions are not allowed together or anything
here is the html
<div class ="signupbox">
<h1>Signup</h1>
<form action="">
<p>Username</p>
<input type="text" id="user" placeholder="Enter Username" pattern="^[a-zA-Z0-9]{8,}$" title="please enter a username with only Letters and numbers[0-9]">
<p>Password</p>
<input name="password" id="password" type="password" placeholder="Enter Password" pattern="(?=.*[a-zA-Z].*)(?=.*[A-Z])(?=.*[0-9])(?=.*[##!%])[a-zA-Z0-9##!%]{6,}" title="please enter a password with at least 1 capital letter and one special from[##!%]" onkeyup='check();'/>
<p>confirm password</p>
<input type="password" name="confirm_password" id="confirm_password" placeholder="confirm Password" onkeyup='check();' />
<span id='message'></span>
<br>
<input type="submit" id="Signup" disabled value="Signup" >
</form>
here is the js
var check = function() {
if (document.getElementById('password').value ==
document.getElementById('confirm_password').value) {
document.getElementById('message').style.color = 'rgb(1, 126, 11)';
document.getElementById('message').style.fontSize="20px"
document.getElementById('message').innerHTML = "Passwords are matching";
} else {
document.getElementById('message').style.color = 'rgba(255, 0, 0, 0.829)';
document.getElementById('message').style.fontSize="20px"
document.getElementById('message').innerHTML = "Passwords are not matching";
sign.disabled=true;
}
}
Simply adding oninput="this.reportValidity()" to all input fields with a pattern, in addition to your onkeyup='check();', will show the browser-based validation feedback.

`Required` attribute not working with <form> tag [duplicate]

This question already has answers here:
HTML5 required attribute not working
(2 answers)
Closed last month.
My required attribute doesn't specify that an input field must be filled out before submitting the form.
HTML:
<!-- Modal Content -->
<form class="modal-content2">
<div class="container3">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="firstName"><b>First Name</b></label>
<input type="text" id="firstName" placeholder="Enter First Name" name="firstName" required>
<label for="lastName"><b>Last Name</b></label>
<input type="text" id="lastName" placeholder="Enter Last Name" name="lastName" required>
<label for="username"><b>Username</b></label>
<input type="text" id="username" placeholder="Enter Username" name="username" required>
<label for="email"><b>Email</b></label>
<input type="text" id="email" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" id="password" placeholder="Enter Password" name="psw" onfocus="this.value=''"
required>
<label for="psw-confirm"><b>Confirm Password</b></label>
<input type="password" id="cfmpassword" placeholder="Confirm Password" name="psw-confirm" onfocus="this.value=''"
required>
<br>
<br>
<p>By creating an account you agree to our <a href="aboutus.html" style="color:dodgerblue">Terms &
Privacy</a>.</p>
<div class="clearfix">
<button type="button" onclick="document.getElementById('id02').style.display='none'" class="cancelbtn2">Cancel</button>
<button type="button" class="signupbtn" onclick="signUp()">Sign Up</button>
</div>
</div>
</form>
JavaScript:
function signUp() {
if (document.getElementById("password").value == document.getElementById("cfmpassword").value) {
var users = new Object();
users.firstName = document.getElementById("firstName").value;
users.lastName = document.getElementById("lastName").value;
users.username = document.getElementById("username").value;
users.email = document.getElementById("email").value;
users.password = document.getElementById("password").value;
var postUser = new XMLHttpRequest(); // new HttpRequest instance to send user details
postUser.open("POST", "/users", true);
postUser.setRequestHeader("Content-Type", "application/json");
postUser.send(JSON.stringify(users));
//go to the logged in page
window.location = "main.html";
}
else {
alert("Password column and Confirm Password column doesn't match!")
}
}
As the required attribute does not work, users can continuously submit empty forms and those will be stored in my SQL database
I don't have a <button type="submit"> in the form as this prevents me from using windows.location.
I am new to programming, can someone please give some suggestions (with explanations) on what to do to fix this? Any help would be appreciated! Thanks a lot! (I am using vanilla JavaScript for this)
The required attribute does not work because your form is not submitted. You need to specify a button with a type="submit" or <input type="submit"> to submit your form.
I suggest you to move the signUp function inside the form tag like this with an onsubmit event:
<form onsubmit="signUp(event)">.
Then add this to you Javascript function:
function signUp(event) {
event.preventDefault();
... your old code
}
For me, I see a number of possible issues. I have tried to remove them with the following sample code. I am assuming that /users will return something useful for checking and alerting the member if there is an error with the accessing of /users or the processing of the data.
The use of the required attribute of <input> will do nothing obvious in your code as the <button> has an onclick=signUp() call which will triggered before the browser check. With your current code the form values (present or not) will still be sent to /users as there is no testing for those values.
You need to move the signUp() call to the <form> if you want the browser check to be run.
To test this, removing the onclick=signUp() in the <button> will show you a browser tip window saying the value is needed.
As you are insisting on using AJAX to post the form data, moving the check to the <form> submit is idea and personally, I would still be checking the values - just good practice.
The next issue is you are not waiting for the return of a success or fail response from /users. In fact, you are blindly redirecting to main.html. If there is an error, the user will never know. This is a very bad user experience.
This is corrected in the sample code by checking for a response with a call-back, checking that response value and then alerting the member or redirecting if there is no error.
var users = {};
function ajaxPost(url,postData,callFunc) {
var http = new XMLHttpRequest();
if(! http){
return false;
}
http.onreadystatechange=function(){
if((http.readyState == 4) && (http.status == 200)) {
if(callFunc){
callFunc(http.responseText);
}
}
}
http.open('POST',url,true);
http.send(postData);
}
function validResult(str) {
if (str == "valid") {
// go to the logged in page
window.location = "main.html";
} else {
console.log("invalid result, let the user know");
}
}
function signUp(e) {
if(e){e.stopPropagation();e.preventDefault();}
var d = document.getElementById("signupForm").querySelectorAll("input");
var i, max = d.length;
// Quick check for values only. No check for the format of the values.
// This is good practice as a browser may still ignore the `required`
// attribute.
for(i=0;i<max;i++) {
d[i].value = d[i].value.trim();
if (d[i].value) {
users[d[i].name] = d[i].value;
} else {
// An alert would be better for the user here.
console.log("Missing value for ["+ d[i].name +"]");
// Go no further if there is a missing value.
return;
}
}
// at this point, all values added to the users object.
console.log("users:["+ JSON.stringify(users) +"]");
// Send the data and wait for a return value from /users
// --- remove comment on the following line to post ----
//ajaxPost("/users",JSON.stringify(users),validResult);
}
window.onload = function(){
var c = document.getElementById("signupForm");
if (c) {
c.addEventListener("submit",signUp,false);
}
}
<form id="signupForm">
<label for="firstName"><b>First Name</b></label>
<input type="text" id="firstName" placeholder="Enter First Name" name="firstName" required>
<p>
<label for="email"><b>Email</b></label>
<input type="email" id="email" placeholder="Enter Email" name="email" required>
<p>
<button id="submit" type="submit">Check and submit</button>
</form>
Basic of HTML5 validation. You have it on button click and that runs before the validation happens. This shows you that the onclick runs and the onsubmit does not. Use the correct event.
function loginSubmit () {
console.log('loginSubmit')
}
function loginClick () {
console.log('loginClick')
}
<form onsubmit="loginSubmit()">
<input name="foo" required />
<button onclick="loginClick()">click</button>
</form>
The way required attribute works is it determines whether the element its assigned to has a value length higher than a zero, if that statement is false (meaning the value length of zero) then upon submitting the form it focuses that element as its "required" to be fulfilled.
Here is an example with JavaScript and how checking input fields could work inside it.
const form = document.querySelector('form[action="signup.php"]'); // Form
const inputs = form.querySelectorAll('input'); // All input elements inside the form
const submit = form.querySelector('button[type="submit"]'); // Submit button inside the form
// Add onclick event to the form button
submit.addEventListener('click', function(event) {
event.preventDefault(); // This prevents the button from submitting the form the traditional way
submit_form(); // but instead our way
});
function submit_form()
{
// We iterate through the form input elements
for (var i = 0; i < inputs.length; i++)
{
// We check if the current element has
// the attribute required and if so
// we proceed with checks
if (inputs[i].hasAttribute('required') && inputs[i].value.length == 0)
{
inputs[i].focus(); // We focus on the required element
alert(inputs[i].placeholder+' is required!'); // Alert the user that the element is required
break; // Break from the loop
}
else
{
if (i == (inputs.length - 1)) form.submit(); // If the loop's i variable counter hits the same value as the
// input elements length then it means all fields are filled
}
}
}
form {
width:300px;
margin:auto
}
form button,
form input {
width:100%;
height:48px;
padding:0 15px;
font-size:18px;
box-sizing:border-box;
}
form input:focus {
background-color:#f2dfb7;
}
<form action="signup.php" method="POST">
<input type="text" name="first_name" placeholder="First Name" required>
<input type="text" name="last_name" placeholder="Last Name" required>
<input type="email" name="email" placeholder="Email Address" required>
<input type="email" name="email_repeat" placeholder="Email Address (Repeat)" required>
<input type="password" name="password" placeholder="Password" required>
<input type="text" name="phone" placeholder="Phone Number" required>
<input type="text" name="birthday" placeholder="Birthday (MM/DD/YYYY)" required>
<button type="submit">Sign Up</button>
</form>

Simple use of the 'required' attribute but also validate the form (to exclude '#')

I’m trying to create a form that ensures the name input field excludes the ‘#‘ symbol but also has the same box appear prompting the user to fill in the field if empty. I assume the box may differ per browser.
To explain my demo further, see this default form:
<form id='form-id' action="/" method="post">
<div class="subscribe-form">
<div class="form-section">
<div>
<input type="text" name="first_name" placeholder="name here" id="name-id" required />
</div>
<div>
<input type="text" name="email" placeholder="Email*" id="email-id" required />
</div>
<input id='checkbox-id' type="checkbox" required /> *check here
</div>
<button type="submit" value="Subscribe">submit</button> <!-- WITH input type submit -->
</div>
</form>
Clicking the submit button will only submit if all fields are completed, but it won’t check if the name field includes an ‘#‘. I can’t edit it to only submit if the field doesn’t include an ‘#‘.
But this demo:
<form id='form-id' action="/" method="post">
<div class="subscribe-form">
<div class="form-section">
<div>
<input type="text" name="first_name" placeholder="name here" id="name-id" required />
</div>
<div>
<input type="text" name="email" placeholder="Email*" id="email-id" required />
</div>
<input id='checkbox-id' type="checkbox" required /> *check here
</div>
<button onclick="checkName()" type="button" value="Subscribe">submit</button> <!-- changed from input type submit -->
</div>
<script>
let form = document.getElementById('form-id'),
ecsName = document.getElementById('name-id'),
ecsEmail = document.getElementById('email-id'),
ecsCheckbox = document.getElementById('checkbox-id');
function checkName() {
let name = ecsName.value,
email = ecsEmail.value;
if(name.includes('#')) {
alert('includes #');
} else if (name == '' || email == '') {
alert('please fill in your details');
} else if (ecsCheckbox.checked == false) {
alert ('unckeded');
} else {
form.submit();
}
}
</script>
</form>
Includes javascript that ensures all fields are completed, but I don’t like the alert and want the same prompt box to appear as with the former form.
Is there any way of doing this? I’m essentially trying to not tamper with the form and let the default settings do most of the work if possible. Also, another quick question - should required be required='required'? Thanks for any help here.

How to validate multiple fieldset in one form tag?

I am working on a form checking. I am stuck on how to stop submitting the form.
So basically, the form has 2 fieldsets (Creat New Customer and Return customer). I have a function which is checking the return customer fieldset if either one of the text field is blank then it will display an message. However, this function also affects on the fieldset (New customer), thus even all the text fields of new customer filled out, it display the message from that function as well. My code:
HTML
<form action="" onsubmit="return loginCheck()">
<fieldset>
<legend>
Create New Account
</legend>
<label>
Account:
<input name="ACCOUNT" size="16" type="text" id="acc"/>
</label>
<label>
Password:
<input name="PW" size="32" type="password" id="pw"/>
</label>
<label>
Password Again:
<input name="PW2" size="32" type="password" id="pw2"/>
</label>
<label>
Email:
<input name="EMAIL" size="32" type="text" id="email"/>
</label>
</fieldset>
<fieldset>
<legend>
Login
</legend>
<label>
Account:
<input name="ACCOUNT" size="16" type="text" id="loginAcc"/>
</label>
<label>
Password:
<input name="PW" size="32" type="password" id="loginPass"/>
</label>
</fieldset>
<input value="Submit" type="submit" id="submit"/>
<input value="Reset" type="reset" id="reset"/>
JS:
function loginCheck() {
var x = document.getElementById("loginAcc");
var y = document.getElementById("loginPass");
if (x.value == "") {
alert("You must type in both fields");
return false;
}
if (y.value == "") {
alert("You must type in both fields");
return false;
}
return true;
}
How can I fix to get that function just check the login fieldset without affect on the create new customer fieldset? Thank you!
You would have to check if the user is trying to enter a new account or his credentials, then check if the form is filled correctly...
function loginCheck() {
var a = document.getElementById("acc");
var b = document.getElementById("pwd");
var c = document.getElementById("pwd2");
var d = document.getElementById("email");
var x = document.getElementById("loginAcc");
var y = document.getElementById("loginPass");
if(a.value!="" || b.value!="" || c.value!="" || d.value!="" ||){
//Do logic to validate creation fieldset.
}else{
//Do logic to validate login
}
return true;
}
There might exist better solutions tough, you could have 2 forms instead of one or something in those lines... What the code above does is really simple, just checks if the user tries to create an account and then validates it. If the user types in his account name in the create form, and notices it is not the right place, then fills the login fields, the script will not work as expected by the user... Try to play with that a bit to find your best solution.

Form Validation without Alerts

I was wondering if there's a way to validate the form without using alerts. Like usually you would see red text beside the input box if you typed in the wrong information or something. And I don't want to use Jquery. I've included a div for the red text messages in the html - namemsg, commentmsg, emailmsg.
So far I've only got the code with alerts.
JavaScript:
function validateUser()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<2 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
{
alert("Valid Input");
}
return true;
}
Html
<form name="myForm" method="post">
<label>*Name:</label>
<input type="text" name="name" title="Enter a your name" placeholder="Your Name" onclick="select()" required/>
<div id="namemsg"></div><br/>
<label>*E-mail:</label>
<input type="text" name="email" title="Enter a valid email address" placeholder="me#example.com" onclick="select()" required/>
<div id="emailmsg"> </div><br/>
<label>*Comment:</label>
<textarea name="comment" title="Enter your comments" placeholder="Enter your comments." onclick="select()" required/></textarea>
<div id="commentmsg"> </div>
<label id="error"> </label> <br/>
<input type="submit" value="Submit" onclick="return validateUser()">
</form>
You can place a span/label next to validated field with predefined text and style and display style of none. If validation detects an invalid input - change the display style to "" to make the label visible.
Update
I do see you have already predefined DIV. Define it as
<div id="emailmsg" style="color:Red;display:none">Not a valid e-mail address</div>
And in JavaScript instead of
alert("Not a valid e-mail address");
Use
document.getElementById("emailmsg").style.display=""
Instead of showing alert message box you can color that textbox borders to red color and show the error beneath it. Like, if you replace the following line of code:
alert("Not a valid e-mail address");
With:
document.forms["myForm"]["email"].style.border = "1px solid red";
document.getElementById("emailmsg").innerHTML = "Not a valid e-mail address";
The above code will highlight the borders of email field with red color and show error in emailmsg div.
Hope this can help.
your html:
<form name="myForm" method="post">
<label>*Name:</label>
<input type="text" name="name" title="Enter a your name" placeholder="Your Name" onclick="select()" required/>
<div id="namemsg"></div><br/>
<label>*E-mail:</label>
<input type="text" name="email" title="Enter a valid email address" placeholder="me#example.com" onclick="select()" required/>
// this span is hidden until you show it as error msg
<span id="error" style='display: none'>Not a valid e-mail address<span>
<div id="emailmsg"> </div><br/>
<label>*Comment:</label>
<textarea name="comment" title="Enter your comments" placeholder="Enter your comments." onclick="select()" required/></textarea>
<div id="commentmsg"> </div>
<label id="error"> </label> <br/>
<input type="submit" value="Submit" onclick="return validateUser()">
</form>
your js:
function validateUser()
{{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<2 || dotpos<atpos+2 || dotpos+2>=x.length)
{
//instead of alerting error show your error span try to put nice css for it
document.getElementById('error').style.display="block";
return false;
}
{alert("Valid Input");}
return true;
}
First, I would recommend attaching the execute of the function to the event OnSubmit.
HTML:
<form method="post" name="myForm" onsubmit="return validateUser(this);">
JS:
function validateUser(formObj) {}
Next, the only thing you need to do, is just have some sort of container, and if the function detects an error, just append the error text to it.
At the start of each function call, empty the container.
If you want the error to appear next to the textbox/any input tag, just add a div/span next to each field and append the error to it.
document.getElementById("emailmsg").innerHTML = "Not cool...";
This should help.
if (atpos<2 || dotpos<atpos+2 || dotpos+2>=x.length){
// validate message function call
valMessage('emailmsg', 'Not a valid e-mail address');
return false;
}
// validate message function
function valMessage(divName, content) {
document.getElementById(divName).innerHTML = content;
}

Categories

Resources