Javascript form validation not working - Script not being called? - javascript

I have a pretty straight-forward javascript form validation script written:
function validateForm(){
var x=document.forms["contactForm"]["firstname"].value;
if (x==null || x==""){
return false;
}
var y=document.forms["contactForm"]["lastname"].value;
if (y==null || y==""){
return false;
}
var z=document.forms["contactForm"]["emailaddress"].value;
var atpos=z.indexOf("#");
var dotpos=z.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=z.length){
return false;
}
var msg_area = document.getElementById("message");
msg_area.innerHTML = "";
if (document.getElementById("message").value.length < 20) {
return false;
}
else document.getElementById("contactForm").submit();
}
It's supposed to be validating this form:
<form name="contactForm" onsubmit="return validateForm()" action="./thankyou.html" method="post">
<label for="firstName">First Name <sup>*</sup></label>
<input name ="firstname" id="firstName" type="text" placeholder="First Name" required />
<label for="lastName">Last Name <sup>*</sup></label>
<input name ="lastname" id="lastName" type="text" name="lastName" placeholder="Last Name" required />
<label for="emailaddress">Email address <sup>*</sup></label>
<input name="emailaddress" id="emailAddress" type="email" placeholder="something#example.com" required />
<label for="message">Message<sup>*</sup></label>
<textarea id="message" placeholder="Remember, be nice!" required></textarea>
<input type="submit" name="submit" value="Email Me!" class="emailsub" />
<p class="small"><sup>*</sup> denotes a required field.</p>
</form>
When it's submitted, it doesn't seem to actually call the javascript at all. The only thing that it looks for is that it meets the "required" part of the html. I'm pretty new to javascript so it's probably glaringly obvious where the problem is, but I just can't locate it myself.
Any help is much appreciated!
p.s. this is for a local website at the moment so the action="" goes to another html instead of a page to process the message. Is this possibly the problem here?

The html5 "required" attribute tells the browser to validate before proceeding, read more here. This means that it's stopping the event before the javascript function is even called (on supported browsers) unless it passes the basic validation (required fields and email).
If you want the javascript to execute and perform your own validation, you'll need to remove the "required" attribute. You may also try more complex html form validation. Here is a good article on the subject.

Related

why is my validation in password not working when connected with html page?

I have created a javascript page and connected it with html page. In the Javascript, i have created validation of the password and if there is a password mismatch then it will alert that there is a mismatch.
function validation()
{
if(password==repassword){
console.log(" ");
}
else{
alert(" ");
}
}
Above code is the javascript code and below is the html code.
LogIn
<label for="username">First Name: </label>
<input class="firstname" type="text" id="firstname" placeholder="First name"><br>
<label for="username">Last Name: </label>
<input class="lastname" type="text" id="lastname" placeholder="Last name"><br>
<label for="email">Email id: </label>
<input class="email" type="email" id="email" placeholder="Email id"><br>
<label for="labeltext">Password: </label>
<input class="password" type="password" id="password" placeholder="Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"><br><br>
<label for="labeltext">Re-Password: </label>
<input class="Re-Password" type="password" id="repassword" placeholder="Re-Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"><br><br>
<button class="Submit" onclick="validation()">Submit</button>
<button class="reset">Reset</button>
</form>
Does anyone know what's wrong in my code? Thank you!
You must create a reference for each element in javascript:
const password = document.getElementById('password');
const repassword = document.getElementById('repassword');
Now your variables are not local and you can use them in your function:
function validation()
{
if(password.value==repassword.value){
console.log(" ");
}
else{
alert(" ");
}
}
I believe what you want to do is to check if the password matches the verify password value.
From your javascript codes, everything looks good but if it is not working, then there is a problem with your HTML elements IDs i.e password field id and verify password field id. Check if you are making a mistake in any of the code you are using to get the element values.
A little mistake like
var x = document.getElementById("txtpass").value;
Where as, in your HTML source, there is no such element with txtpass as id could cause your javascript codes to break.
I would advise you post the complete HTML and Javascript codes.
Better still, use your browser console to check for the runtime error that is depriving your code from running as expected.
Use name=password in your password and name=repassword in your repassword tag like
<input class="password" name="password" type="password" id="password" placeholder="Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"><br><br>

`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>

Why doesnt required work to validate my forms?

I am trying to validate some text-fields using the required keyword, yet nothing is working?
How do I create validation using the required keyword.
Here is my code:
<div id="Name" class="tabcontent">
<form>
<div class="nameDiv">
Title: <input type="text" name="Title" title="Title" id="TitleTransfer">
</div>
<br>
<div class="addressDiv">
Name: <input type="text" name="name" id="NameTransfer" required />
<span class="asterisk"></span>
</div>
<br>
<div class="emailDiv">
Surname:
<input type="text" name="surname" id="LastNameTransfer" required />
<span class="asterisk"></span>
</div>
<br>
<div class="numberDiv">
Email Address:
<input type="text" name="email Address" id="EmailTransfer" required />
<span class="asterisk"></span>
</div>
<br>
<div class="numberDiv">
Phone number:
<input type="text" name="Phone number" id="NumberTransfer">
</div>
<button id="save-btnOne" onclick="moveContentOne()">Save</button>
</form>
</div>
the required attributes tells the browser that the form field must contain something, this is a weak validation and can be supressed when hooking the form submit through javascript (keep in mind that you do not have delivered any kind of javascript source here that might be in the orbit of the form).
I assume that the moveContentOne() hooking the onclick-event is the only javascript attached. Considering this the onSubmit-event remains untouched and will be also fired alongside of your onClick intervention. You should prefer to hook onSubmit for forms of that kind to apply custom validation, but that might detach the browser's default behavior for form validation (including the required-attachment to fields).
You might take a look at this guide: Form data validation
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
Use this type of validation.
This works for
<form name="myForm" onsubmit="validateForm()">
<input type="text" name="fname" />
</form>
Some browsers do not support required field.
Change the code to your need.
I hope it helps you.

How to check if the required attribute is set on a field

I have a simple form that has some required fields in it.
<form name="form" method="post">
<pre>
<label> Name: </label><input type="text" name="name" required>
<label> Address: </label><input type="text" name="add" required>
<label>Telephone: </label><input type="text" name="tel">
<input type="submit" value="Submit Form">
</pre>
</form>
I know you can set the required attribute using document.forms['form']['name'].required = false. But is there a way where you can just check if the required attribute is set or not? I tried using getattribute() but it just returns blank. I also tried using the code below, but it always executes the statement, even if the required attribute isn't set (e.g. on the telephone field).
if( document.forms['form']['name'].required = true)
label.innerHTML += " (required)"
Does anyone know of a way I can do this?
Update: Both setting the if statement to == instead of = and using hasAttribute work, thanks.
Try this :
var elem = document.getElementsByTagName('input')[0];
if(elem.hasAttribute('required')){
//do your stuff
}

JavaScript Not Submitting Form

I've spent the last hour or so trawling through here and Google without success. I have a form that I want to submit via POST. The javascript runs and validates fine, it even 'submits' the form. But when it does, it just reloads the page. No POST headers are sent (confirmed using Firebug in Firefox). It's as though it simply reloads the page rather than submitting it.
This form is embedded in the addUser.php page.
<form action="addUser.php" method="post" name="NewUser">
<div data-role="field-contain">
<label label-for="EmpID" class="ui-hidden-accessible">Enter Employee ID</label>
<input name="EmpID" id="EmpID" placeholder="Employee ID" value="" autocomplete="off" title="Enter Employee ID" type="number" required autofocus>
<label label-for="UserName" class="ui-hidden-accessible">Enter username</label>
<input name="UserName" id="UserName" placeholder="Username" value="" autocomplete="off" title="Enter the new username" required>
<p>
<label label-for="NewPass1" class="ui-hidden-accessible">Enter Your Current Password</label>
<input name="NewPass1" id="NewPass1" placeholder="New Password" value="" type="password" autocomplete="off" title="Must be at least 8 characters, with numbers and upper and lower case letters." required>
</p>
<p>
<label label-for="NewPass2" class="ui-hidden-accessible">Enter Your Current Password</label>
<input name="NewPass2" id="NewPass2" placeholder="Verify Password" value="" type="password" autocomplete="off" title="Re-enter your chosen new password." required>
</p>
</div>
<button type="button" name="submitButton" value="submitButton" data-theme="d" data-inline="true" data-icon="check" data-iconpos="left" onclick="validateForm ()">
Add User
</button>
And here is the Javascript:
function validateForm()
{
var reason = "";
reason += validateEmpID();
reason += validateUserName();
reason += validateNewPassword();
if (reason != "") {
alert("There are some errors with the data you entered:\n" + reason);
return false;
} else {
document.NewUser.submit();
}
}
I have tried various different methods of calling submit, all with the same result. Any help greatly appreciated.
Thanks
Gareth
I think it should be
document.forms['NewUser'].submit();
or
document.forms.NewUser.submit();
I think somewhere you are missing adding return false that is the reason your browser is asking for reloading the form. And better way to submit is to use submit button instead of using simple button.
Why not use an AJAX post? Or better yet a jQuery AJAX POST?
$.post(url, data, datatype);
http://api.jquery.com/jQuery.post/
function validateForm(event) {
var reason = "";
reason += validateEmpID();
reason += validateUserName();
reason += validateNewPassword();
if (reason != "") {
alert("There are some errors with the data you entered:\n" + reason);
event.preventDefault();
}
}
document.getElementById('my_form').addEventListener('submit', validateForm, false);

Categories

Resources