Form submits even though it is not passing validation through JavaScript - javascript

I'm making a simple form and have made a function for each field to validate. But when I test the form via live server, the form submits even if the fields don't validate. Each function seems to work as intended aside from that.
function validateForm () {
var firstName = document.getElementById('fname').value;
var phoneNumber = document.getElementById('phonenumber').value;
function firstNameValid () {
if (firstName == "") {
console.log("First name empty")
return false;
} else {
return true;
};
};
firstNameValid();
function phoneValid () {
if (phoneNumber == null || phoneNumber == "" || phoneNumber.length < 10) {
console.log("Phone number must be defined and not exceed 10 characters")
return false;
} else {
return true;
}
};
phoneValid();
result = firstNameValid() && phoneValid();
};
<body>
<form name="registration" action="page2.html" onsubmit="return validateForm()" method="GET">
<ul>
<li>
<label for="fname">First Name:</label><br>
<input type="text" id="fname" name="fname" onsubmit="return firstNameValid()"><br>
</li>
<li>
<label for="phonenumber">Phone Number:</label><br>
<input type="text" id="phonenumber" name="phonenumber" onsubmit="return phoneValid()">
</li>
</ul>
<button type="submit" value="Submit">Submit</button>
</form>
<script src="app.js"> </script>
</body>

You're not returning the result variable
result = firstNameValid() && phoneValid();
return result;

You should return the result.
function validateForm() {
var firstName = document.getElementById('fname').value;
var phoneNumber = document.getElementById('phonenumber').value;
function firstNameValid () {
if (firstName == "") {
console.log("First name empty")
return false;
} else {
return true;
};
};
function phoneValid () {
if (phoneNumber == null || phoneNumber == "" || phoneNumber.length < 10) {
console.log("Phone number must be defined and not exceed 10 characters")
return false;
} else {
return true;
}
};
return firstNameValid() && phoneValid();
};
<body>
<form name="registration" action="page2.html" onsubmit="return validateForm()" method="GET">
<ul>
<li>
<label for="fname">First Name:</label><br>
<input type="text" id="fname" name="fname"><br>
</li>
<li>
<label for="phonenumber">Phone Number:</label><br>
<input type="text" id="phonenumber" name="phonenumber">
</li>
</ul>
<button type="submit" value="Submit">Submit</button>
</form>
</body>

Related

The action attribute if the HTML form element is not working

I want to redirect to another html page named formPreview.html after validation and form submit so I specified action attribute with the value "formPreview.html" but after passing the validation when the submit button is clicked is not going to that page
function showValidationError(message) {
var errorDiv = document.createElement("div");
errorDiv.setAttribute("id", "error-banner");
var errorSpan = document.createElement("span");
errorSpan.textContent = message;
errorSpan.setAttribute("class", "error-text");
errorDiv.appendChild(errorSpan);
body.appendChild(errorDiv);
}
// ----------------------Validating each field----------------------
function validate() {
if (numPresent.test(firstName.value)) {
return [firstName, false];
}
if (numPresent.test(lastName.value)) {
return [lastName, false];
}
if (isNaN(Number(phone.value))) {
return [phone, false];
}
if (phone.value.length < 10) {
return [phone, false];
}
if (age.value <= 0) {
return [age, false];
}
return true;
}
// ----------------------Registering form submit events----------------------
form.addEventListener("submit", (e) => {
e.preventDefault();
if (validate() === true) {
console.log("Form Submitted");
} else {
let array = validate();
if (array[0].id === "phone-input") {
showValidationError("Please enter the valid phone number");
}
if (array[0].id === "first-name-input") {
showValidationError("Enter a valid firstname");
}
if (array[0].id === "last-name-input") {
showValidationError("Enter a valid lastname");
}
if (array[0].id === "age-input") {
showValidationError("Enter a valid age");
}
}
});
<div class="container">
<form class="form" action="formPreview.html" method="GET">
<div id="input-name">
<label for="first-name-input" class="form-label">First Name</label>
<input type="text" placeholder="First Name" id="first-name-input" required />
<label for="last-name-input" class="form-label">Last Name</label>
<input type="text" placeholder="Last Name" id="last-name-input" required />
</div>
<div id="input-email-phone">
<label for="email-input" class="form-label">Email</label>
<input type="email" placeholder="someone#example.com" id="email-input" required />
<label for="phone-input" class="form-label">Contact</label>
<input type="tel" placeholder="+xx xxxxx xxxxx" id="phone-input" required />
</div>
<div id="address">
<label for="address-input" class="form-label">Address</label>
<input type="text" placeholder="Full address with ZIP Code " id="address-input" required />
</div>
</form>
Several issues
you always preventDefault (which is submit)
give the form an ID if you want to access the submit event
Clear the errors and don't create one if already there
No age field
fields not defined in script
You COULD use patterns like [a-zA-Z-'] to not have to test the name using script but I would not limit people to type what they wanted into a field.
const numPresent = /\d+/
function showValidationError(message) {
let errorSpan = document.getElementById("error-span");
errorSpan.textContent = message;
document.getElementById("error-banner").hidden = false;
}
// ----------------------Validating each field----------------------
function validate() {
document.getElementById("error-banner").hidden = true;
const firstName = document.getElementById("first-name-input")
if (numPresent.test(firstName.value)) {
return [firstName, false];
}
const lastName = document.getElementById("last-name-input")
if (numPresent.test(lastName.value)) {
return [lastName, false];
}
const phone = document.getElementById("phone-input")
if (isNaN(Number(phone.value))) {
return [phone, false];
}
if (phone.value.length < 10) {
return [phone, false];
}
/* no age field
if (age.value <= 0) {
return [age, false];
} */
return true;
}
// ----------------------Registering form submit events----------------------
document.getElementById("form1").addEventListener("submit", (e) => {
let array = validate(); // DRY
if (array === true) { // overloading the array to be true or an array ?
console.log("Form Submitted");
return;
}
e.preventDefault();
if (array[0].id === "phone-input") {
showValidationError("Please enter the valid phone number");
}
if (array[0].id === "first-name-input") {
showValidationError("Enter a valid firstname");
}
if (array[0].id === "last-name-input") {
showValidationError("Enter a valid lastname");
}
if (array[0].id === "age-input") {
showValidationError("Enter a valid age");
}
});
<div class="container">
<form class="form" action="formPreview.html" method="GET" id="form1">
<div id="input-name">
<label for="first-name-input" class="form-label">First Name</label>
<input type="text" placeholder="First Name" id="first-name-input" required />
<label for="last-name-input" class="form-label">Last Name</label>
<input type="text" placeholder="Last Name" id="last-name-input" required />
</div>
<div id="input-email-phone">
<label for="email-input" class="form-label">Email</label>
<input type="email" placeholder="someone#example.com" id="email-input" required />
<label for="phone-input" class="form-label">Contact</label>
<input type="tel" placeholder="+xx xxxxx xxxxx" id="phone-input" required />
</div>
<div id="address">
<label for="address-input" class="form-label">Address</label>
<input type="text" placeholder="Full address with ZIP Code " id="address-input" required />
</div>
<input type="submit" />
</form>
</div>
<div id="error-banner" hidden>
<span id="error-span" class="error-text"></span>
</div>

Why does my JavaScript seems to not run in my HTML

Sorry for any formatting error, first time posting.
Sorry if similar of this is already answered, I couldn't find it anywhere (or I'm just bad at searching).
I'm doing a page to register user to my website, my javascript doesn't work and I can't find what's wrong with it.
My html file does not display the alertbox which supposed to run if I leave my box empty, putting in the wrong characters, etc.
registration.html
<!DOCTYPE html>
<html lang="en"><head>
<meta charset="utf-8">
<title>Registration Form</title>
</head>
<body onLoad="document.registration.userID.focus();">
<h1>Registration Form</h1>
<form name="registration" onSubmit="return validation();">
<label for="userID">User ID</label><br><input id="userID" name="userID" placeholder="Enter your ID" type="text"/><br>
<label for="userPass">Password</label><br><input id="userPass" name="userPass" placeholder="Enter your password" type="password" /><br>
<label for="userName">Username</label><br><input id="userName" name="userName" placeholder="Enter your username" type="text" /><br>
<label for="addr">Address</label><br><input id="addr" name="addr" placeholder="eg. Tamara Residence" type="text" /><br>
<label for="ctry">Country</label><br><select id="ctry" name="ctry">
<option value="DEF">Please select your country</option>
<option value="MY">Malaysia</option>
<option value="IN">India</option></select><br>
<label for="zip">Zip Code</label><br><input id="zip" name="zip" placeholder="eg. 25565" type="text" /><br>
<label for="email">Email</label><br><input id="email" name="email" placeholder="eg. nikfarisaiman109#gmail.com" type="text" /><br>
Sex<br>
<input type="radio" id="1" name="sex" value="1">
<label for="1">Male</label><br>
<input type="radio" id="2" name="sex" value="2">
<label for="2">Female</label><br>
Language<br>
<input type="checkbox" id="EN" name="EN" value="English">
<label for="EN">English</label><br>
<input type="checkbox" id="MY" name="MY" value="Malay">
<label for="MY">Malay</label><br>
<label for="about">About</label><br>
<textarea id="about" name="about" rows="4" cols="50">
</textarea><br><br>
<input name="submit" type="submit" value="Register" />
</form>
<script src="formValidation.js" type="text/javascript"></script>
</body>
</html>
formValidation.js
function validation(){
var userID = document.registration.userid;
var userPass = document.registration.password;
var userName = document.registration.name;
var addr = document.registration.address;
var ctry = document.registration.country;
var zip = document.registration.zip;
var email = document.registration.email;
var sex = document.registration.sex;
if (userID_validate(userID,5,12)) {
if (userPass_validate(userPass,7,12)) {
if (alphabet_validate(userName)) {
if (alphanumeric_validate(addr)) {
if (empty_validate(ctry)) {
if (allnumeric_validate(zip)) {
if (emailformat_validate(email)) {
if (sex_validate(sex)) {
}
}
}
}
}
}
}
}
return false;
}
function userID_validate(userID,a,b) {
//length of string
var userID_length = userID.value.length;
if (userID_length == 0 || userID_length >= a || userID_length < b) {
alert("ID should not be empty / length should be between " + a + " to " + b + " characters");
userID.focus();
return false;
}
return true;
}
function userPass_validate(userPass,a,b) {
//length of string
var userPass_length = userPass.value.length;
if (userPass_length == 0 || userPass_length >= a || userPass_length < b) {
alert("Password should not be empty / length should be between " + a + " to " + b + " characters");
userPass.focus();
return false;
}
}
function alphabet_validate(userName) {
var betReg = /^[A-Za-z]+$/;
if (userName.value.match(betReg)) {
return true;
}
else {
alert("Username should only contain alphabet");
userName.focus();
return false;
}
}
function alphanumeric_validate(addr) {
var betnumReg = /^[0-9A-Za-z]+$/;
if (addr.value.match(betnumReg)) {
return true;
}
else {
alert("Address can only be alphanumeric");
addr.focus();
return false;
}
}
function empty_validate(ctry) {
if(ctry.value == "DEF"){
alert("Please select a country");
ctry.focus();
return false;
}
else
return true;
}
function allnumeric_validate(zip) {
var numReg = /^[0-9]+$/;
if (zip.value.match(numReg)) {
return true;
}
else {
alert("ZIP Code should only contain only numbers");
zip.focus();
return false;
}
}
function emailformat_validate(email) {
var emailReg = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
if(email.value.match(emailReg))
return true;
else {
alert("Please enter in a correct email address format");
email.focus();
return false;
}
}
function sex_validate(sex) {
var formValid = false;
var x = 0;
while (!formValid && x < document.getElementById("sex").length) {
if (document.getElementById("sex")[x].checked)
formValid = true;
x++;
}
if (!formValid){
alert("Please select male or female");
sex.focus();
return false;
}
else {
alert("Form successfully submitted, thank you for registering!");
window.location.reload();
return true;
}
}
Did you check the error on Console via doing Inspect Element? I copied the same code as you mentioned in Question and getting this error in Console.
Uncaught TypeError: userID is undefined
In your formValidation.js, please update the
var userID = document.registration.userid;
With correct userID as follow.
var userID = document.registration.userID;
Try putting the <script> into <head>

when onsubmit event in form only first function is working i want to return all 3 function with true

Ajax code to check email is new or existing
I want all the three function return(checkpass() && check() && validate(this)) to work. Currently only the function checkpass() is working. If I write return(check() && checkpass() && validate(this)), only check() function gets triggered.
function check(){
var uname=document.forms["register_form"]["uname"].value;
var uemail=document.forms["register_form"]["uemail"].value;
var upassword=document.forms["register_form"]["upassword"].value;
var ucpassword=document.forms["register_form"]["ucpassword"].value;
if(uname=="" || uemail=="" || upassword=="" || ucpassword==""){
alert("all fields must be filled out");
return false;
}
}
function checkpass(){
var upass=document.forms["register_form"]["upassword"].value;
var ucpass=document.forms["register_form"]["ucpassword"].value;
if(upass!=ucpass){
alert("Confirm password should be same as password");
return false;
}
if(upass=="" && ucpass==""){
alert("cannot be kept blank");
return false;
}
}
function validate(useremail){
xhttp =new XMLHttpRequest();
xhttp.open("GET","emailvalidate.php?uemail="+useremail,true);
xhttp.send();
xhttp.onreadystatechange=function(){
if (xhttp.readyState == 4) {
if(xhttp.responseText==""){
document.getElementById("alert").innerHTML="cannot be empty";
return false;
}
else if(xhttp.responseText=="OK"){
document.getElementById("alert").innerHTML="<span class='badge badge-pill badge-primary'>welcome new user</span>";
}
else if(xhttp.responseText=="NO"){
document.getElementById("alert").innerHTML="<span class='badge badge-pill badge-primary'>Email Already Exist</span>";
return false;
}
else{
document.getElementById("alert").innerHTML="error happened";
return false;
}
}
};
}
<form method="post" action="register_action.php" id="register_form" name="register_form" onsubmit="return (checkpass() && check() && validate(this));">
<br>
<div class="form-group">
<label for="uname">Name:</label>
<input type="text" class="form-control" id="uname" placeholder="Enter Name " name="uname">
</div>
<div class="form-group">
<label for="uemail">Email id: </label>
<input type="email" class="form-control" id="uemail" placeholder="Enter Email ID" name="uemail"
onkeyup="javascript:validate(this.value)"><br>
<span id="alert"></span>
</div>
<div class="form-group">
<label for="upassword">Enter Password:</label>
<input type="password" class="form-control" id="upassword" placeholder="Set password" name="upassword">
</div>
<div class="form-group">
<label for="ucpassword">Confirm Password:</label>
<input type="password" class="form-control" id="ucpassword" placeholder="Enter password again" name="ucpassword" >
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
Why don't you wrap them in a function:
var wrapper = function(){
return checkpass() && check() && validate(this);
}
and then
<form onsubmit="javascript:wrapper()">
Also, you can curry this chain of functions to increase readability but well, the example above must resolve your problem.

Validation message doesn't show

Good day everyone! My problem is why the firstName & lastName error message not showing. The username & password error message is working fine. Even if the password and confirm password error is working fine. The only problem is when my firstName and lastName is empty no error message show. I already download the jQuery and include it to my head tag. I double check the id names if same with my html. I think there are same. Can somebody help me regarding to my problem? I will show you my codes below!
$(function() {
$("#firstname_errors").hide(); //hide the span tag
$("#lastname_errors").hide(); //hide the span tag
var error_firstnames = false;
var error_lastnames = false;
$("#form_firstnames").focusout(function() {
check_firstname();
});
$("#form_lastnames").focusout(function() {
check_lastname();
});
function check_firstname() {
var firstname = $("#form_firstnames").val();
if (firstname == "") {
$("#firstname_errors").html("Firstname is empty");
$("#firstname_errors").show();
$("#firstname_errors").addClass("formError");
error_firstnames = true;
} else {
$("#firstname_errors").hide();
}
}
function check_lastname() {
var lastname = $("#form_lastnames").val();
if (lastname == "") {
$("#lastname_errors").html("Lastname is empty");
$("#lastname_errors").show();
$("#lastname_errors").addClass("formError");
error_lastnames = true;
} else {
$("#lastname_errors").hide();
}
}
$("#registration_forms").submit(function() {
error_firstnames = false;
error_lastnames = false;
check_firstname();
check_lastname();
if (error_firstname = false && error_lastname = false) {
return true;
} else {
return false;
}
});
});
<form id=registration_forms action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<div>
<label for="fname">First Name: </label>
<input type="text" name="fname" id="form_firstnames" placeholder="First Name" autocomplete="off">
<span id="firstname_errors"></span> //error message
</div>
<div>
<label for="lname">Last Name: </label>
<input type="text" name="lname" id="form_lastnames" placeholder="Last Name" autocomplete="off">
<span id="lastname_errors"></span> //error message
</div>
<div>
<input type="submit" name="btnSave" value="Register">
</div>
Already a member? Login
</form>
This line is wrong:
if (error_firstname = false && error_lastname = false)
It's doing assignment, not comparison. Change that if/else to:
return !error_firstnames && !error_lastnames;
$(function() {
$("#firstname_errors").hide(); //hide the span tag
$("#lastname_errors").hide(); //hide the span tag
var error_firstnames = false;
var error_lastnames = false;
$("#form_firstnames").focusout(function() {
check_firstname();
});
$("#form_lastnames").focusout(function() {
check_lastname();
});
function check_firstname() {
var firstname = $("#form_firstnames").val();
if (firstname == "") {
$("#firstname_errors").html("Firstname is empty");
$("#firstname_errors").show();
$("#firstname_errors").addClass("formError");
error_firstnames = true;
} else {
$("#firstname_errors").hide();
}
}
function check_lastname() {
var lastname = $("#form_lastnames").val();
if (lastname == "") {
$("#lastname_errors").html("Lastname is empty");
$("#lastname_errors").show();
$("#lastname_errors").addClass("formError");
error_lastnames = true;
} else {
$("#lastname_errors").hide();
}
}
$("#registration_forms").submit(function() {
error_firstnames = false;
error_lastnames = false;
check_firstname();
check_lastname();
return !error_firstnames && !error_lastnames;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id=registration_forms action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<div>
<label for="fname">First Name: </label>
<input type="text" name="fname" id="form_firstnames" placeholder="First Name" autocomplete="off">
<span id="firstname_errors"></span> //error message
</div>
<div>
<label for="lname">Last Name: </label>
<input type="text" name="lname" id="form_lastnames" placeholder="Last Name" autocomplete="off">
<span id="lastname_errors"></span> //error message
</div>
<div>
<input type="submit" name="btnSave" value="Register">
</div>
Already a member? Login
</form>

Form validation not working in chrome nor firefox

Im working with this contact form.
<form name="contact" action="mailto:me#me.com&subject=subject&body=message"
onsubmit="return validate()" method="post" enctype="text/plain">
<label for="mail">Your mail address *</label>
<input type="text" name="mail"/></br></br>
<label for="subject">Subject *</label>
<input type="text" name="subject"/></br>
<label for="message">Your message *</label>
<textarea id="txtarea" name="message" form="contact"></textarea>
<input type="submit" value="Send"/>
</form>
And this javascript
function validateMail(mail) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)| (\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(mail);
}
function validate(){
var x = document.forms["contact"];
if (x[0].value == null || x[0].value == ""){
alert("Your mail address");
return false;
}else{
if(!validateMail(x[0].value)){
alert("mail address not valid");
return false;
}
}
if(x[1].value == null || x[1].value == ""){
alert("Add a subject");
return false;
}
if(x['txtarea'].value.length < 1 || x['txtarea'].value == '' || x['txtarea'].value == null){
alert("Add your message");
return false;
}
}
This code works perfectly on IE11 (11.0.9600.18500) but chrome 54.0.2840.71 m (64-bit) and FF 49.0.2 just ignore my javascript and proceed to send the mail with empty fields or not valid info.
PS: im using id for the textarea since i cant find it with the form[#] option
Edit: I found that IE properly identifies the textarea as [object HTML TextAreaElement] but for both chrome and firefox is undefined
The problem is with your textarea, remove form="contact" from it. You can use the below form -
<form name="contact" action="mailto:me#me.com&subject=subject&body=message" onsubmit="return validate()" method="post" enctype="text/plain">
<label for="mail">Your mail address *</label>
<input type="email" name="mail" /></br>
</br>
<label for="subject">Subject *</label>
<input type="text" name="subject" /></br>
<label for="message">Your message *</label>
<textarea id="txtarea" name="message"></textarea>
<input type="submit" value="Send" />
</form>
And here is little optimized Javascript function for your form-
function validateMail(mail) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)| (\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(mail);
}
function validate() {
var x = document.forms["contact"];
if (!x[0].value) {
alert("Your mail address");
return false;
} else {
if (!validateMail(x[0].value)) {
alert("mail address not valid");
return false;
}
}
if (!x[1].value) {
alert("Add a subject");
return false;
}
if (!x['txtarea'].value) {
alert("Add your message");
return false;
}
}
Managed to solve it by using:
if(document.getElementById('txtarea').value.length < 1 || document.getElementById('txtarea').value == '' || document.getElementById('txtarea').value == null)
instead of:
if(x['txtarea'].value.length < 1 || x['txtarea'].value == '' || x['txtarea'].value == null)
since neither chrome or firefox can properly process form['id']

Categories