Javascript form validation - can't validate multiple fields - javascript

I am trying to get a form with multiple fields validate when the submit button is pressed.
If a field is invalid then a message appears next to the field. I can get one of the invalid messages to appear but not all of them. The function I am using is below.
function checkForm() {
document.getElementById("test").onsubmit=function(){
var title = document.getElementById("titles");
if (title.selectedIndex == -1) {
return null;
}
var email = document.getElementById('email');
//Regular Expression for checking email
var emailRegEx = /[-\w.]+#([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}/;
if (!emailRegEx.test(email.value)) {
document.getElementById("errEmail").style.display="inline";
return false;
}
if(document.getElementById("fname").value==""){
document.getElementById("errfName").style.display="inline";
return false;
}
else {
return true;
}
if(document.getElementById("lname").value==""){
document.getElementById("errlName").style.display="inline";
return false;
}
else {
return true;
}
}
}
html below
<form name ="reg" id="test">
<fieldset id="controls">
<div>
<label for="title">Title: </label>
<select id="titles">
<option value="mr" selected="selected">Title</option>
<option value="mr">Mr.</option>
<option value="mrs">Mrs.</option>
<option value="ms">Ms.</option>
<option value="miss">Miss</option>
</select>
</div>
<div>
<label for="fname">First Name: </label>
<input id="fname" type="text"><span id="errfName" class="error">* Please Enter a First Name</span>
</div>
<div>
<label for="lname">Last Name: </label>
<input id="lname" type="text"><span id="errlName" class="error">* Please Enter a Last Name</span>
</div>
<div>
<label for="email">Email: </label>
<input id="email" type="text" size="40"><span id="errEmail" class="error">* Please enter a valid email</span>
</div>
<div>
<input type="submit" value="submit">
</div>
</fieldset>
</form>
</body>
</html>

try this:
function checkForm() {
var errors = [];
document.getElementById("test").onsubmit=function(){
var title = document.getElementById("titles");
if (title.selectedIndex == -1) {
return null;
}
var email = document.getElementById('email');
//Regular Expression for checking email
var emailRegEx = /[-\w.]+#([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}/;
if (!emailRegEx.test(email.value)) {
errors.push("errEmail");
}
if(document.getElementById("fname").value==""){
errors.push("errfName");
}
if(document.getElementById("lname").value==""){
errors.push("errlName");
}
if(errors.length > 0 ){
for(var i=0;i<errors.length;i++){
document.getElementById(errors[i]).style.display="inline";
}
return false;
}else{
return true
}
}
}

Related

Disabling a button on empty <select> list?

`I've created a form that allows a user to enter their details and have their first and last names displayed along with a numerical ID. There is a 'Delete' button allowing the user to remove whatever name they select.
by default, the 'Delete' button should be disabled until the <select> list is populated. If all names are deleted from the list - the 'Delete' button should disable again.
That's where im struggling. I cant get the 'Delete' button to enable when a name is added to the list.
Below is my HTML and JavaScript:
MemberList
<h1>Member List</h1>
<form method="post" id="_frmFull">
<label for="lstMembers">Member:</label>
<select size="10"
name="lstMembers"
id="lstMembers">
</select>
<button type="button"
id="addMember"
name="Add Member">
Add Member
</button>
<button type="button"
name="Delete Member"
id="delete">
Delete Member</button>
<div id="Modal" class="modal">
<div class="modal-form">
<label for="memTitle">Title:</label>
<input list="memTitles" name="memTitles" id="memTitle">
<datalist id="memTitles">
<option value="Dr">
<option value="Mr">
<option value="Mrs">
<option value="Ms">
</datalist>
<label for="firstName">First Name:</label>
<input type="text" name="firstName" id="firstName" required="required">
<label for="middleName">Middle Name (optional):</label>
<input type="text" name="middleName" id="middleName">
<label for="lastName">Last Name:</label>
<input type="text" name="lastName" id="lastName" required="required">
<br><br>
<label for="Country">Country:</label>
<input list="countries" name="Country" id="Country">
<datalist id="countries">
<option value="Australia">
<option value="United Kingdom">
<option value="America">
<option value="New Zealand">
</datalist>
<label for="Gender">Gender:</label>
<select name="Gender" id="Gender">
<option>Male</option>
<option>Female</option>
<option>Other</option>
</select>
<label for="birthDate">Birthdate:</label>
<input type="date"
id="birthDate"
min="1900-01-01"
max="2022-12-31" required="required">
<br><br>
<div id="resiAddress">
<p>Residential Address:</p>
<br>
<label for="txtResidentialAddress">Address:</label>
<input type="text" required="required" id="txtResidentialAddress" oninput="copyAddressFields();">
<br><br>
<label for="txtResiPostCode">Postcode:</label>
<input type="text" required="required" id="txtResiPostCode">
<br><br>
<label for="txtResiSuburb">Suburb:</label>
<input type="text" required="required" id="txtResiSuburb">
<br><br>
<label for="txtResiCountry" class="country">Country</label>
<input type="text" required="required" id="txtResiCountry">
<br><br>
<label for="txtResiState">State:</label>
<input type="text" required="required" id="txtResiState">
</div>
<br><br>
<label for="chkSynchronizeAddresses">Same as residential </label>
<input type="checkbox" required="required" id="chkSynchronizeAddresses" >
<div id="postAddress">
<p>Postal Address:</p>
<br>
<label for="txtPostalAddress">Address:</label>
<input type="text" id="txtPostalAddress">
<br><br>
<label for="txtPostCode">Postcode:</label>
<input type="text" id="txtPostCode">
<br><br>
<label for="txtPostalSuburb">Suburb:</label>
<input type="text" id="txtPostalSuburb">
<br><br>
<label for="txtPostalCountry">Country:</label>
<input type="text" id="txtPostalCountry">
<br><br>
<label for="txtPostalState">State:</label>
<input type="text" id="txtPostalState">
</div>
<br><br>
<label for="txtPhone" class="phone">Phone: (optional)</label>
<input id="txtPhone" type="text">
<br><br>
<label for="txtMobile" class="mobile">Mobile: (optional)</label>
<input id="txtMobile" type="text">
<br><br>
<button type="button" name="save" id="save">Save</button>
<br><br>
<button type="button"
name="cancel"
id="closeModal">
Cancel</button>
</div>
</div>
</form>
<script>
console.log("Log test - please work!!")
const addBtn = document.getElementById("addMember");
const modal = document.getElementById("Modal");
const cancelBtn = document.getElementById("closeModal");
let chkSynchronizeAddresses = document.getElementById("chkSynchronizeAddresses");
const _frmFull = document.getElementById("_frmFull");
let Member = document.getElementById("lstMembers");
let Delete = document.getElementById("delete");
let save = document.getElementById("save");
let fName = document.getElementById("firstName");
let lName = document.getElementById("lastName");
let birthDate = document.getElementById("birthDate");
Delete.disabled = Member.value === 1;
addBtn.onclick = function (){
openPopUp();
console.log('function - correct');
}
cancelBtn.onclick = function (){
let closeTrue = confirm("Close form? You've not saved anything.")
if (closeTrue === true) {
closePopUp();
}
}
chkSynchronizeAddresses.onclick = function (){
console.log("Is this working??");
if (chkSynchronizeAddresses.checked){
document.getElementById("txtPostalAddress").setAttribute("readonly", "true");
document.getElementById("txtPostCode").setAttribute("readonly", "true");
document.getElementById("txtPostalState").setAttribute("readonly", "true");
document.getElementById("txtPostalSuburb").setAttribute("readonly", "true");
document.getElementById("txtPostalCountry").setAttribute("readonly", "true");
copyAddressFields();
}
else {
document.getElementById("txtPostalAddress").removeAttribute("readonly");
document.getElementById("txtPostCode").removeAttribute("readonly")
document.getElementById("txtPostalState").removeAttribute("readonly");
document.getElementById("txtPostalSuburb").removeAttribute("readonly");
document.getElementById("txtPostalCountry").removeAttribute("readonly");
}
}
function copyAddressFields () {
if (chkSynchronizeAddresses.checked){
document.getElementById("txtPostalAddress").value = document.getElementById("txtResidentialAddress").value;
document.getElementById("txtPostCode").value = document.getElementById("txtResiPostCode").value;
document.getElementById("txtPostalSuburb").value = document.getElementById("txtResiSuburb").value;
document.getElementById("txtPostalState").value = document.getElementById("txtResiState").value;
document.getElementById("txtPostalCountry").value = document.getElementById("txtResiCountry").value;
}
}
let idCount = 0
save.onclick = function (){
let fNameValue = fName.value
let lNameValue = lName.value
let bDateValue = birthDate.value
let pCountryValue = document.getElementById("txtPostalCountry").value
let pSuburbValue = document.getElementById("txtPostalSuburb").value
let pStateValue = document.getElementById("txtPostalState").value
let pCodeValue = document.getElementById("txtPostCode").value
let pAddressValue = document.getElementById("txtPostalAddress").value
if (fNameValue === ""){
alert("Please enter your first name to proceed");
return false;
}
else
if (lNameValue === "") {
alert("Please enter your last name to proceed");
return false;
} else if (bDateValue === "") {
alert("Please select a DOB to proceed");
return false;
} else if (pCountryValue === "") {
alert("Please enter your country to continue");
return false;
} else if (pSuburbValue === "") {
alert("Please enter your suburb to continue");
return false;
} else if (pCodeValue === "") {
alert("Please enter your postcode to continue");
return false;
} else if (pAddressValue === "") {
alert("Please enter your Address to continue");
return false;
} else if (pStateValue === "") {
alert("Please enter your state to continue");
return false;
} else {
Member.innerHTML +=
`<option value= >${idCount} ${_frmFull.firstName.value} ${_frmFull.lastName.value}<option>`
idCount++
console.log("check - is increase even working????")
}
closePopUp();
return true;
}
function closePopUp() {
modal.style.display="none";
}
function openPopUp() {
modal.style.display = "block";
}
Delete.onclick = function removeOption () {
Member.remove(Member.options);
console.log("is remove being triggered??")
}
if (Member.options.length == ""){
Delete.disabled = true
}
else {
Delete.disabled = false
}
</script>
</body>
`
The reason why the Delete button is not enabling is because the code that is supposed to enable the Delete button is only run once, when the page loads.
Assuming that this is the code that is supposed to enable the button:
if (Member.options.length == 0){ // changed from Member.options.length == ""
Delete.disabled = true
} else {
Delete.disabled = false
}
This code is only run once, when the page loads and the JavaScript code is run. In order to enable the button properly, we need to run this code every time that Member.options.length changes. One way you can do this is place the code snippet above for disabling/enabling the Delete button inside the onclick listener for the save button and to re-check every time a new user is saved. You would have to add this snippet into every place in your code where Member.options.length could change (inside the listener for the delete button as well).
Full updated code:
MemberList
<h1>Member List</h1>
<form method="post" id="_frmFull">
<label for="lstMembers">Member:</label>
<select size="10"
name="lstMembers"
id="lstMembers">
</select>
<button type="button"
id="addMember"
name="Add Member">
Add Member
</button>
<button type="button"
name="Delete Member"
id="delete">
Delete Member</button>
<div id="Modal" class="modal">
<div class="modal-form">
<label for="memTitle">Title:</label>
<input list="memTitles" name="memTitles" id="memTitle">
<datalist id="memTitles">
<option value="Dr">
<option value="Mr">
<option value="Mrs">
<option value="Ms">
</datalist>
<label for="firstName">First Name:</label>
<input type="text" name="firstName" id="firstName" required="required">
<label for="middleName">Middle Name (optional):</label>
<input type="text" name="middleName" id="middleName">
<label for="lastName">Last Name:</label>
<input type="text" name="lastName" id="lastName" required="required">
<br><br>
<label for="Country">Country:</label>
<input list="countries" name="Country" id="Country">
<datalist id="countries">
<option value="Australia">
<option value="United Kingdom">
<option value="America">
<option value="New Zealand">
</datalist>
<label for="Gender">Gender:</label>
<select name="Gender" id="Gender">
<option>Male</option>
<option>Female</option>
<option>Other</option>
</select>
<label for="birthDate">Birthdate:</label>
<input type="date"
id="birthDate"
min="1900-01-01"
max="2022-12-31" required="required">
<br><br>
<div id="resiAddress">
<p>Residential Address:</p>
<br>
<label for="txtResidentialAddress">Address:</label>
<input type="text" required="required" id="txtResidentialAddress" oninput="copyAddressFields();">
<br><br>
<label for="txtResiPostCode">Postcode:</label>
<input type="text" required="required" id="txtResiPostCode">
<br><br>
<label for="txtResiSuburb">Suburb:</label>
<input type="text" required="required" id="txtResiSuburb">
<br><br>
<label for="txtResiCountry" class="country">Country</label>
<input type="text" required="required" id="txtResiCountry">
<br><br>
<label for="txtResiState">State:</label>
<input type="text" required="required" id="txtResiState">
</div>
<br><br>
<label for="chkSynchronizeAddresses">Same as residential </label>
<input type="checkbox" required="required" id="chkSynchronizeAddresses" >
<div id="postAddress">
<p>Postal Address:</p>
<br>
<label for="txtPostalAddress">Address:</label>
<input type="text" id="txtPostalAddress">
<br><br>
<label for="txtPostCode">Postcode:</label>
<input type="text" id="txtPostCode">
<br><br>
<label for="txtPostalSuburb">Suburb:</label>
<input type="text" id="txtPostalSuburb">
<br><br>
<label for="txtPostalCountry">Country:</label>
<input type="text" id="txtPostalCountry">
<br><br>
<label for="txtPostalState">State:</label>
<input type="text" id="txtPostalState">
</div>
<br><br>
<label for="txtPhone" class="phone">Phone: (optional)</label>
<input id="txtPhone" type="text">
<br><br>
<label for="txtMobile" class="mobile">Mobile: (optional)</label>
<input id="txtMobile" type="text">
<br><br>
<button type="button" name="save" id="save">Save</button>
<br><br>
<button type="button"
name="cancel"
id="closeModal">
Cancel</button>
</div>
</div>
</form>
<script>
console.log("Log test - please work!!")
const addBtn = document.getElementById("addMember");
const modal = document.getElementById("Modal");
const cancelBtn = document.getElementById("closeModal");
let chkSynchronizeAddresses = document.getElementById("chkSynchronizeAddresses");
const _frmFull = document.getElementById("_frmFull");
let Member = document.getElementById("lstMembers");
let Delete = document.getElementById("delete");
let save = document.getElementById("save");
let fName = document.getElementById("firstName");
let lName = document.getElementById("lastName");
let birthDate = document.getElementById("birthDate");
Delete.disabled = Member.options.length == 0
addBtn.onclick = function (){
openPopUp();
console.log('function - correct');
}
cancelBtn.onclick = function (){
let closeTrue = confirm("Close form? You've not saved anything.")
if (closeTrue === true) {
closePopUp();
}
}
chkSynchronizeAddresses.onclick = function (){
console.log("Is this working??");
if (chkSynchronizeAddresses.checked){
document.getElementById("txtPostalAddress").setAttribute("readonly", "true");
document.getElementById("txtPostCode").setAttribute("readonly", "true");
document.getElementById("txtPostalState").setAttribute("readonly", "true");
document.getElementById("txtPostalSuburb").setAttribute("readonly", "true");
document.getElementById("txtPostalCountry").setAttribute("readonly", "true");
copyAddressFields();
}
else {
document.getElementById("txtPostalAddress").removeAttribute("readonly");
document.getElementById("txtPostCode").removeAttribute("readonly")
document.getElementById("txtPostalState").removeAttribute("readonly");
document.getElementById("txtPostalSuburb").removeAttribute("readonly");
document.getElementById("txtPostalCountry").removeAttribute("readonly");
}
}
function copyAddressFields () {
if (chkSynchronizeAddresses.checked){
document.getElementById("txtPostalAddress").value = document.getElementById("txtResidentialAddress").value;
document.getElementById("txtPostCode").value = document.getElementById("txtResiPostCode").value;
document.getElementById("txtPostalSuburb").value = document.getElementById("txtResiSuburb").value;
document.getElementById("txtPostalState").value = document.getElementById("txtResiState").value;
document.getElementById("txtPostalCountry").value = document.getElementById("txtResiCountry").value;
}
}
let idCount = 0
save.onclick = function (){
let fNameValue = fName.value
let lNameValue = lName.value
let bDateValue = birthDate.value
let pCountryValue = document.getElementById("txtPostalCountry").value
let pSuburbValue = document.getElementById("txtPostalSuburb").value
let pStateValue = document.getElementById("txtPostalState").value
let pCodeValue = document.getElementById("txtPostCode").value
let pAddressValue = document.getElementById("txtPostalAddress").value
if (fNameValue === ""){
alert("Please enter your first name to proceed");
return false;
}
else
if (lNameValue === "") {
alert("Please enter your last name to proceed");
return false;
} else if (bDateValue === "") {
alert("Please select a DOB to proceed");
return false;
} else if (pCountryValue === "") {
alert("Please enter your country to continue");
return false;
} else if (pSuburbValue === "") {
alert("Please enter your suburb to continue");
return false;
} else if (pCodeValue === "") {
alert("Please enter your postcode to continue");
return false;
} else if (pAddressValue === "") {
alert("Please enter your Address to continue");
return false;
} else if (pStateValue === "") {
alert("Please enter your state to continue");
return false;
} else {
Member.innerHTML +=
`<option value= >${idCount} ${_frmFull.firstName.value} ${_frmFull.lastName.value}<option>`
idCount++
console.log("check - is increase even working????")
if (Member.options.length == 0){
Delete.disabled = true
}
else {
Delete.disabled = false
}
}
closePopUp();
return true;
}
function closePopUp() {
modal.style.display="none";
}
function openPopUp() {
modal.style.display = "block";
}
Delete.onclick = function removeOption () {
Member.remove(Member.options);
if (Member.options.length == 0) {
Delete.disabled = true
}
else {
Delete.disabled = false
}
console.log("is remove being triggered??")
}
</script>
</body>
so if i understood correctly you want to toggle a button if a is populated
In that case you want to keep track of the options
You can use
document.querySelectoAll('options')
and store it in a variable
then write a function that check if there's a value in that variable and disable or enable the button based on that.
Here's a fiddle:
https://jsfiddle.net/skm7bcr6/15/

JavaScript can not get alert box

So basically, I'm trying to do client side validation through JavaScript, but the code does not seem to be working. I am not getting any alert box. Below is HTML Form and JavaScript. I have skipped html and Body tags for obvious reasons. Can someone look over and see where am I making a mistake?
HTML form
<div class="container" >
<h1 style="text-align: center;">Online Vaccine Registration Form</h1>
<h1 style="text-align: center;">Developed by yourname</h1>
<form method="post" name="vacform" onsubmit=" return validateForm()">
<table>
<div class="row">
<div class="form-group col-md-6">
<label for="Name">Name : </label>
<input type="text" class="form-control" name="name" placeholder="Name">
</div>
<div class="form-group col-md-6">
<label for="CNIC" >CNIC : </label>
<input type="text" class="form-control" name="CNIC" placeholder="CNIC">
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="Mob">Mobile : </label>
<input type="number" class="form-control" name="Mob" placeholder="Mobile">
</div>
<div class="form-group col-md-6">
<label for="Dob" >DoB : </label>
<input type="date" class="form-control" name="DoB">
</div>
</div>
<div class="form-group">
<label for="cen">Nearby centre</label>
<select class="form-control" id="sel1">
<option selected disabled>Select your Nearest Centre</option>
<option>Karachi West</option>
<option>Karachi East</option>
<option>Karachi North</option>
<option>Karachi Central</option>
<option>Malir</option>
</select>
</div>
</table>
<button type="button" class="btn btn-primary">Submit</button>
</form>
</div>
JavaScript
function validateForm()
{
var varname = document.vacform.name.value;
var varcnic = document.vacform.CNIC.value;
var varMob = document.vacform.Mob.value;
var varDoB = new Date(DoB);
var limitdate = new Date('2010-01-01');
var CNlength = 13;
var num = /^[0-9]+$/;
var str = /^[A-Za-z]+$/;
if(document.vacform.name.value!="")
{
if(document.vacform.CNIC.value!="")
{
if(document.vacform.Mob.value!="")
{
if(document.vacform.DoB.value!="")
{
if(varname.match(str))
{
if(varcnic.lenght == CNlength)
{
if(varcnic.match(num))
{
if(varDoB.getYear() < limitdate.getYear())
{
alert("All types of Validations have been done")
return true;
}
else
{
alert("Date should be less than 01-01-2010")
return false;
}
}
else
{
alert("CNIC field should have numbers only")
return false;
}
}
else
{
alert("CNIC lenght should be 13")
return false;
}
}
else
{
alert("Name can only contain letters")
return false;
}
}
else
{
alert("Date of Birth must be entered")
return false;
}
}
else
{
alert("Please Enter your mobile number")
return false;
}
}
else
{
alert("CNIC number Required")
return false;
}
}
else
{
alert("Name field can not be empty")
return false;
}
}
</script>
You call the function from the onsubmit event handler, however you never submit the form so it can't be triggered.
<button type="button" class="btn btn-primary">Submit</button>
This kind of button is for hooking JS into. It isn't a submit button.
Set type="submit" or remove the type attribute entirely (submit is the default).
Also address the errors in your HTML that a validator would highlight.

html form validation using javascript

i am trying to validate my html form using javascript. the validation works but it still submits.
ie. when clicking submit a text will appear saying "first name is required" but then still submits.
here is the javascript code:
function validateForm(form) {
formValid = true;
for(i = 0; i < form.length; i++) {
if(!requiredInput(form[i]))
formValid = false;
}
return formValid;
}
function requiredInput(element) {
if(!element.value.length) {
document.getElementById(element.id + 'Error').style.display = "inline-block";
return false;
} else {
document.getElementById(element.id + 'Error').style.display = "none";
return true;
}
return;
}
and here is the html code for the form:
<form action="http://tl28dfdsdsserv.westernsydney.edu.au/twainfo/echo.php" method="get" onsubmit="return validateForm(this);">
<h2>Validate you name:</h2>
<div>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" placeholder="Given Name" onblur="requiredInput(this);">
<span class="error" id="fnameError">First Name is Required</span>
</div>
<div>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lname" placeholder="Surname" onblur="requiredInput(this);">
<span class="error" id="lnameError">Last Name is Required</span>
</div>
<div>
<hr>
</div>
<div>
<input type="submit" value="Submit" name="submit" >
</div>
</form>
im not sure why it still submits.
EDIT: i need to debug this code and not change all of it
EDIT: i can not change the html code for this, i am to debug the javascript only
I think you need validate if its type submit :
function validateForm(form) {
formValid = true;
for(i = 0; i < form.length; i++) {
if(form[i].type != "submit"){
if(!requiredInput(form[i])){
formValid = false;
}
}
}
return formValid;
}
Your validation has the correct structure, however, if there is any JavaScript error, the "return false" will not cancel the form submission.
Go to your developer console and manually invoke the validateForm function. You can give the form an ID:
<form id="myform"...
Then, you can reference this in the console:
validateForm(document.getElementById('form'));
You will see a JavaScript error. Fix the error and your form will be intercepted.
<form action="http://tl28dfdsdsserv.westernsydney.edu.au/twainfo/echo.php" method="get"
onsubmit="return validateForm(event)">
<h2>Validate you name:</h2>
<div>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" placeholder="Given Name" onblur="requiredInput(this);">
<span class="error" id="fnameError">First Name is Required</span>
</div>
<div>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lname" placeholder="Surname" onblur="requiredInput(this);">
<span class="error" id="lnameError">Last Name is Required</span>
</div>
<div>
<hr>
</div>
<div>
<input type="submit" value="Submit" name="submit">
</div>
<script type="text/javascript">
function validateForm(e) {
form = e.target;
formValid = true;
for (i = 0; i < form.length; i++) {
if (!requiredInput(form[i]))
formValid = false;
}
return formValid;
}
function requiredInput(element) {
if (element.type == 'submit') {
return true;
}
if (element.value.length == 0) {
document.getElementById(element.id + 'Error').style.display = "inline-block";
return false;
} else {
document.getElementById(element.id + 'Error').style.display = "none";
return true;
}
}
this should work
Actually You can do it simple way, see below,
Modify your HTML
I remove onsubmit attribute and add form to ID
<form id="dsds" action="http://tl28dfdsdsserv.westernsydney.edu.au/twainfo/echo.php" method="get">
<h2>Validate you name:</h2>
<div>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" placeholder="Given Name" onblur="requiredInput(this);">
<span class="error" id="fnameError">First Name is Required</span>
</div>
<div>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lname" placeholder="Surname" onblur="requiredInput(this);">
<span class="error" id="lnameError">Last Name is Required</span>
</div>
<div>
<hr>
</div>
<div>
<input type="submit" value="Submit" name="submit" >
</div>
Remove your JS function and do like this,
$("#dsds").submit(function(e){
//call your functions here
return false; // return true if you want to submit the form
});
See the example,
JSFille
Use preventDefault() to disable the submit.
function validateForm(event, form) {
formValid = true;
for (i = 0; i < form.length; i++) {
if (!requiredInput(form[i])) {
formValid = false;
break;
}
}
if (!formValid) {
event.preventDefault();
}
return formValid;
}
And pass the event object in the onsubmit function like below.
<form action="http://tl28dfdsdsserv.westernsydney.edu.au/twainfo/echo.php" method="get" onsubmit="validateForm(event, this);">
function validateForm(form) {
formValid = true;
try {
for (i = 0; i < form.length; i++) {
if (!requiredInput(form[i]))
formValid = false;
}
} catch (error) {
console.error("validateForm=>", error)
}
return formValid;
}
function requiredInput(element) {
try {
const elementInputError = document.getElementById(element.id + 'Error');
if (!element.value.length) {
elementInputError && setDisplayError(elementInputError,"inline-block");
return false;
} else {
elementInputError && setDisplayError(elementInputError,"none");
return true;
}
} catch (error) {
console.error("requiredInput=>", error)
return false;
}
}
function setDisplayError(element,value) {
try {
element.style.display =value;
} catch (error) {
console.error("setDisplayError=>", error)
}
}
<form action="http://tl28dfdsdsserv.westernsydney.edu.au/twainfo/echo.php" method="get"
onsubmit="return validateForm(this);">
<h2>Validate you name:</h2>
<div>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" placeholder="Given Name" onblur="requiredInput(this);">
<span class="error" id="fnameError">First Name is Required</span>
</div>
<div>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lname" placeholder="Surname" onblur="requiredInput(this);">
<span class="error" id="lnameError">Last Name is Required</span>
</div>
<div>
<hr>
</div>
<div>
<input type="submit" value="Submit" name="submit">
</div>
</form>
The problem arose because it also validated the send button and because it did not have the termination of the failed id it could not find the item and an error occurred. Then when the error occurred it did not return anything the function and redirect you to the form action page.

Javascript Validation form onsubmit not returning false

Note : i searched similar questions and still couldn't fix it so i'm asking again.
i have a form and its onsubmit = "return submit()". it checks if textarea is empty. If it is then it returns false but that doesn't work.The action still goes to the next website even if text area is empty.
let firstName = document.querySelector('#firstname');
let lastName = document.querySelector('#lastname');
let password = document.querySelector('#password');
let retypePass = document.querySelector('#repassword');
let radioMale = document.querySelector('#male');
let radioFemale = document.querySelector('#female');
let textArea = document.querySelector('#textarea');
let select= document.querySelector('#select');
let button = document.querySelector('#button');
let form = document.querySelector('#form');
function submit(){
if (textArea.value = "") {
textArea.nextElementSibling.innerHTML = "Fill this box";
return false;
}
}
HTML :`
<div class='wrapper'>
<h1>Registration Form</h1>
<form action="http://google.com" id='form' onsubmit="return submit()">
<input placeholder="First Name" type="text" id='firstname' required>
<span></span>
<br>
<input placeholder="Last Name" type="text" id='lastname' required>
<span></span>
<br>
<input placeholder="Password" type="text" id='password' required>
<span></span>
<br>
<input placeholder="Retype Password" type="text" id='repassword' required>
<span></span>
<br>
<input placeholder="Phone Number" type="tel" id='tel' >
<br>
<div class='radio'>
<h4>Selector Your Gender</h4>
<input type='radio'name='same' id='male'>Male
<input type='radio'name='same' id='female'>Female
</div>
<p style="margin:5px 0px;color:white">ADDRESS:</p>
<textarea id='textarea'></textarea>
<span></span>
<p style="margin:5px 0px;color:white">Country:</p>
<select type='country' style="width:84%" id='select'>
<option>England</option>
<option>Japan</option>
<option>America</option>
<option>France</option>
<option>NetherLands</option>
</select>
<br><br>
<input type='submit' value='submit'>
</form>
</div>
Your if systax was wrong:
if (textArea.value = "")
It should be:
if (textArea.value == "")
You must change the name of the function
Example
<form action="http://google.com" id='form' onsubmit="return validate()">
and
function validate() {
if (textArea.value == "") {
textArea.nextElementSibling.innerHTML = "Fill this box";
return false;
}
}
try
if (!textArea.value) {
textArea.nextElementSibling.innerHTML = "Fill this box";
return false;
}
OR
if (textArea.value == '') {
textArea.nextElementSibling.innerHTML = "Fill this box";
return false;
}

form validation problems with jquery / javascript

This is my first real project which involves form validation. I am experiancing a problem which I can not find the solution to.
The objective is this, there is a continue button which will be activated once all the field inputs have been passed as valid. I am going about this by creating seperate variables, all initially set as false, devoted to checking each input field. When the user has entered correct validation data, the variable is set to true.
I then run an if statement to check if all the variables are set to true, and if so, I activate the continue button which, when clicked, slides the next part of the form into the page.
HTML:
<div class="container">
<h3>Step 3: Your Details</h3>
<!-- SLIDE-IN DIV TO REPRESENT DAY PASS -->
<div class="row chosenmembership">
<div class="col-md-12 text-center" id="yourdetails">
<form action="" method="">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" placeholder="Email Address" id="email" class="form-control your-details">
<span class="warning" id="email-warning"></span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" placeholder="Full Name" id="name" class="form-control your-details">
<span class="warning" id="name-warning"></span>
</div>
<div class="form-group">
<label for="number">Contact Number:</label>
<input type="text" placeholder="Contact Number" id="number" class="form-control your-details">
<span class="warning" id="number-warning"></span>
</div>
<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" class="form-control your-details">
<span class="warning" id="dob-warning"></span>
</div>
</form>
<input type="submit" id="submit" value="CONTINUE">
</div>
</div>
</div>
JAVASCRIPT / JQUERY:
//collection of input form fields//
var formSubmit = $("#submit");
var emailField = $("#email");
var nameField = $("#name");
var numberField = $("#number");
//Switch to true when each validation has passed//
emailValidated = false;
nameValidated = false;
numberValidated = false;
//email validation check//
emailField.on("input",function(){
var emailInput = $(this).val()
var testExp = new RegExp(/[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$/);
if (emailInput < 1) {
$("#email-warning").html("Email is required!");
$("#email-warning").css("visibility","visible");
emailValidated = false;
}
else if (!testExp.test(emailInput)){
$("#email-warning").html("Please enter a valid email");
$("#email-warning").css("visibility","visible");
emailValidated = false;
} else {
$("#email-warning").css("visibility","hidden");
emailValidated = true;
}
})
//name validation check//
nameField.on("input",function(){
var nameInput = $(this).val()
if (nameInput < 1) {
$("#name-warning").html("Name is required");
$("#name-warning").css("visibility","visible");
nameValidated = false;
} else {
$("#name-warning").css("visibility","hidden");
nameValidated = true;
}
})
//contact number validation check//
numberField.on("input",function(){
var numberInput = $(this).val()
if (typeof numberInput !== "number" && numberInput.length < 9) {
$("#number-warning").html("Please enter a valid number");
$("#number-warning").css("visibility","visible");
numberValidated = false;
} else {
$("#number-warning").css("visibility","hidden");
numberValidated = true;
}
})
if (emailValidated && nameValidated && numberValidated){
alert("correct");
}
})
at the moment, I am simply using the alert prompt to test if it is working, but it fails.
As mentioned, this is my first real form validation. Any other tips or advice would be greatly appreciated. Thanks for the help in advance.
There were a couple things that I found from copying pasting your snippets of code. 1 there was an ending "})" without a beginning $(document).ready(function(){ ". 2 none of your ".on" statements had an ending semi colon.
Here is my javascript with a small change
$(document).ready(function () {
//collection of input form fields//
var formSubmit = $("#submit");
var emailField = $("#email");
var nameField = $("#name");
var numberField = $("#number");
//Switch to true when each validation has passed//
emailValidated = false;
nameValidated = false;
numberValidated = false;
//email validation check//
emailField.on("input", function () {
var emailInput = $(this).val()
var testExp = new RegExp(/[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$/);
if (emailInput < 1) {
$("#email-warning").html("Email is required!");
$("#email-warning").css("visibility", "visible");
emailValidated = false;
}
else if (!testExp.test(emailInput)) {
$("#email-warning").html("Please enter a valid email");
$("#email-warning").css("visibility", "visible");
emailValidated = false;
} else {
$("#email-warning").css("visibility", "hidden");
emailValidated = true;
enableContinue();
}
});
//name validation check//
nameField.on("input", function () {
var nameInput = $(this).val()
if (nameInput < 1) {
$("#name-warning").html("Name is required");
$("#name-warning").css("visibility", "visible");
nameValidated = false;
} else {
$("#name-warning").css("visibility", "hidden");
nameValidated = true;
enableContinue();
}
});
//contact number validation check//
numberField.on("input", function () {
var numberInput = $(this).val()
if (typeof numberInput !== "number" && numberInput.length < 9) {
$("#number-warning").html("Please enter a valid number");
$("#number-warning").css("visibility", "visible");
numberValidated = false;
} else {
$("#number-warning").css("visibility", "hidden");
numberValidated = true;
enableContinue();
}
});
enableContinue = function () {
if (emailValidated && nameValidated && numberValidated) {
$('#submit').prop('disabled', false);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h3>Step 3: Your Details</h3>
<!-- SLIDE-IN DIV TO REPRESENT DAY PASS -->
<div class="row chosenmembership">
<div class="col-md-12 text-center" id="yourdetails">
<form action="" method="">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" placeholder="Email Address" id="email" class="form-control your-details">
<span class="warning" id="email-warning"></span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" placeholder="Full Name" id="name" class="form-control your-details">
<span class="warning" id="name-warning"></span>
</div>
<div class="form-group">
<label for="number">Contact Number:</label>
<input type="text" placeholder="Contact Number" id="number" class="form-control your-details">
<span class="warning" id="number-warning"></span>
</div>
<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" class="form-control your-details">
<span class="warning" id="dob-warning"></span>
</div>
</form>
<input type="submit" class="btn btn-primary" id="submit" disabled="disabled" value="CONTINUE">
</div>
</div>
</div>
Your form CONTINUE button becomes enables once all fields have a value. Note: I did not try to improve your javascript any, just made it work.
Right now you synchronically check validation variables at script, so they are all false. You have to asynchronically check them after form submit. Just add event listener to form submit to check variables like this:
document.getElementById('#form').addEventListener('submit', function(){
if (emailValidated && nameValidated && numberValidated){
alert("correct");
}
});
Don't forget to set id to your form.
You may be able to save a lot of work if you leverage some of the built in HTML5 form validation. https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation
This simple example adds a new field every time you submit the form, as long as the existing fields are valid. You would need to test the state of the form to see if you should be adding another section or submitting.
$('form').on('submit', function() {
$(this).find('fieldset').append('<input type="text" required />');
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<input type="text" required />
</fieldset>
<input type="submit" id="submit" value="continue" />
</form>

Categories

Resources