validity API to validate a form - javascript

I'm trying to validate a form with validity API, but have some issues (2 to be precise) . One for valueMissing where the textContent couldn't be displayed and the second when submitting the form (all fiels are corect then) : nothing happen, I can't see the console.log. Here is the code
html
const formValid = document.getElementById('myButton');
formValid.addEventListener('click', valid);
// function valid() : allow sending form after checking it
function valid(e) {
e.preventDefault();
let isFormOk = true;
let fname = document.getElementById('fname');
let missFname = document.getElementById('fname_missing');
let firstNameValue = document.getElementById('fname').value;
let email = document.getElementById('email');
let missEmail = document.getElementById('email_missing');
let emailValue = document.getElementById('email').value;
let fnameValid = /^[a-zA-ZéèîïÉÈÎÏ][a-zéèêàçîï]+([-'\s][a-zA-ZéèîïÉÈÎÏ][a-zéèêàçîï]+)?$/;
let emailValid = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
//Validate the firstname :
if (fname.validity.valueMissing) { //if the field is empty
missFname.textContent = 'Enter your firstname please!';
missFname.style.color = 'red';
isFormOk = false;
}
if (fnameValid.test(fname.value) == false) { // if the format is incorrect
missFname.textContent = 'Incorrect format';
missFname.style.color = 'black';
isFormOk = false;
}
//Validate the email :
if (email.validity.valueMissing) {
missEmail.textContent = 'Email missing';
missEmail.style.color = 'red';
isFormOk = false;
}
if (emailValid.test(email.value) == false) {
missEmail.textContent = 'Incorrect format';
missEmail.style.color = 'black';
isFormOk = false;
}
if (isFormOk) {
let contact = {
firstNameValue,
emailValue
};
console.log(contact);
}
<form novalidate id="myForm">
<div class="form-group">
<input type="text" class="form-control" name="fname" id="fname" required>
<span id="fname_missing"></span>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" required>
<span id="email_missing" class="errorMail" aria-live="polite"></span>
</div>
<div class="form-group">
<button id="myButton" name="myButton" type="submit">Confirm</button>
</div>
</form>

const formValid = document.getElementById('myButton');
formValid.addEventListener('click', valid);
// function valid() : allow sending form after checking it
function valid(e) {
e.preventDefault();
let isFormOk = true;
let fname = document.getElementById('fname');
let missFname = document.getElementById('fname_missing');
let firstNameValue = document.getElementById('fname').value;
let email = document.getElementById('email');
let missEmail = document.getElementById('email_missing');
let emailValue = document.getElementById('email').value;
let fnameValid = /^[a-zA-ZéèîïÉÈÎÏ][a-zéèêàçîï]+([-'\s][a-zA-ZéèîïÉÈÎÏ][a-zéèêàçîï]+)?$/;
let emailValid = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
//Validate the firstname :
if (fname.validity.valueMissing) { //if the field is empty
missFname.textContent = 'Enter your firstname please!';
missFname.style.color = 'red';
isFormOk = false;
}
if (fnameValid.test(fname.value) == false) { // if the format is incorrect
missFname.textContent = 'Incorrect format';
missFname.style.color = 'black';
isFormOk = false;
}
//Validate the email :
if (email.validity.valueMissing) {
missEmail.textContent = 'Email missing';
missEmail.style.color = 'red';
isFormOk = false;
}
if (emailValid.test(email.value) == false) {
missEmail.textContent = 'Incorrect format';
missEmail.style.color = 'black';
isFormOk = false;
}
if (isFormOk) {
let contact = {
firstNameValue,
emailValue
};
missEmail.style.display = 'none';
missFname.style.display = 'none';
console.log(contact);
}
return isFormOk;
}
<form novalidate id="myForm">
<div class="form-group">
<input type="text" class="form-control" name="fname" id="fname" required>
<span id="fname_missing"></span>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" required>
<span id="email_missing" class="errorMail" aria-live="polite"></span>
</div>
<div class="form-group">
<button id="myButton" name="myButton" type="submit">Confirm</button>
</div>
</form>
There is a curly brace missing in javascript function. Check this if it answers your question.

Related

Form Submission failed

I have an issue while submitting a form its giving me error that >validateform()is not defined
before it was working.
It is loan application in which I have to send an email once user submit form with correct details and also generate random 4 digit no which will be in email which user will receive
<script src="https://smtpjs.com/v3/smtp.js">
## Heading ##
function validateForm() {
let name = document.forms["myForm"]["fullName"].value;
let email = document.forms["myForm"]["email"].value;
let pan = document.forms["myForm"]["pan"].value;
let lamount = document.forms["myForm"]["flamnt"].value;
let regName = /\d+$/g;
let regEmail = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/g;
let regPan = /^([a-zA-Z]){5}([0-9]){4}([a-zA-Z]){1}?$/;
//captcha validation
let input_val = document.getElementById('input_val');
let num1 = document.getElementById('num1');
let num2 = document.getElementById('num2');
const mybtn = document.getElementById('btn');
//returns a random integer from 0to9
num1.innerText = Math.floor(Math.random() * 10);
num2.innerText = Math.floor(Math.random() * 10);
let number1 = num1.innerText;
let number2 = num2.innerText;
enter code here
mybtn.addEventListener("click", () => {
//
let sum_result = parseInt(number1) + parseInt(number2);
let res = parseInt(input_val.value);
if (res == sum_result) {
alert("correct");
}
else {
alert("Incorrect")
}
window.location.reload();
});
if (name == "" || regName.test(name)) {
alert("Name must be filled out");
return false;
}
if (email == "" || !regEmail.test(email)) {
alert("Please enter a valid e-mail address.");
return false;
}
if (pan == "" || !regPan.test(pan)) {
alert("Please enter a valid PAN no.");
return false;
}
//OTP generation
const generateOtp = () =>{
let otp = "";
for(let i=0 ; i < 4 ; i++){
otp += Math.floor(Math.random() * 10);
}
//if we write return otp directly then this will return otp in string
return Number(otp); //this will return otp as number.
};
console.log("OTP:", generateOtp());
}
//sending an email
// function sendEmail() {
// Email.send({
// Host: "smtp.gmail.com",
// Username: "...#gmail.com",
// Password: "....",
// To: document.getElementById("email").value,
// From: "....#gmail.com",
// Subject: "Thank you for Inquiry",
// Body: "Well that was easy!!",
// })
// .then(function (message) {
// alert("mail sent successfully")
// });
// }
</script>
</head>
<body>
<div class="form-container">
<h1>Loan Application Form</h1>
<form name="myForm" method="post" action="thankyou.html" onsubmit="validateForm();">
<div class="formdesign" id="name">
Full Name:<input type="text" class="form-control" placeholder="Enter your fullname" name="fullName"><span
class="formerror"></span>
</div>
<div class="formdesign" id="email">
Email:<input type="email" class="form-control" placeholder="Enter email" name="email"><span
class="formerror"></span>
</div>
<div class="formdesign" id="panno">
PAN No:<input type="text" class="form-control" placeholder="Like BBHPM5672K" name="pan" maxlength="10"><span
class="formerror"></span>
</div>
<div class="formdesign" id="lamount">
Loan Amount:<input type="number" class="form-control" placeholder="Enter loan amount" name="flamnt"><span
class="formerror"></span>
</div>
<div class="formdesign">
Enter Captcha:<input type="text" placeholder="enter captcha" class="form-control" id="input_val" />
<p id="operation"><span id="num1">1</span> + <span id="num2">2</span></p>
<button id="bttn" class="captcha-refresh"><i class="fa fa-refresh"></i>Refresh</button>
</div>
<input id="btn" class="button" type="submit" value="Submit">
<input class="button" type="reset" value="Reset">
</form>
You have many issues
You do not have a closing </script> for your <script src="https://smtpjs.com/v3/smtp.js"> and a starting <script> for your code.
Please try to use the snippet editor [<>] and remove the "enter code here" and ## Heading ##
You need to use the submit event and e.preventDefault is stopping the submit. I changed name="myForm" to id="myForm", forms do not need names
You are adding event listeners in the validation.
You were missing the refresh function
Here is what I believe you need
const generateOtp = () => {
let otp = "";
for (let i = 0; i < 4; i++) {
otp += Math.floor(Math.random() * 10);
}
//if we write return otp directly then this will return otp in string
return Number(otp); //this will return otp as number.
};
document.getElementById('bttn').addEventListener("click", e => {
e.preventDefault();
let num1 = document.getElementById('num1');
let num2 = document.getElementById('num2');
//returns a random integer from 0to9
num1.innerText = Math.floor(Math.random() * 10);
num2.innerText = Math.floor(Math.random() * 10);
})
document.getElementById("myForm").addEventListener("submit", (e) => {
const form = e.target;
let name = form["fullName"].value;
let email = form["email"].value;
let pan = form["pan"].value;
let lamount = form["flamnt"].value;
let regName = /\d+$/g;
let regEmail = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/g;
let regPan = /^([a-zA-Z]){5}([0-9]){4}([a-zA-Z]){1}?$/;
//captcha validation
let input_val = document.getElementById('input_val');
let num1 = document.getElementById('num1');
let num2 = document.getElementById('num2');
let number1 = num1.innerText;
let number2 = num2.innerText;
let errors = [];
let sum_result = parseInt(number1) + parseInt(number2);
let res = parseInt(input_val.value);
if (res != sum_result) errors.push("Sum not correct");
if (name == "" || regName.test(name)) errors.push("Name must be filled out");
if (email == "" || !regEmail.test(email)) errors.push("Please enter a valid e-mail address.");
if (pan == "" || !regPan.test(pan)) errors.push("Please enter a valid PAN no.");
if (errors) {
alert(errors.join("\n"));
e.preventDefault();
return
}
//OTP generation
console.log("OTP:", generateOtp()); // not sure what you want with this
// sendEmail()
})
//sending an email
// function sendEmail() {
// Email.send({
// Host: "smtp.gmail.com",
// Username: "...#gmail.com",
// Password: "...",
// To: document.getElementById("email").value,
// From: "...#gmail.com",
// Subject: "Thank you for Inquiry",
// Body: "Well that was easy!!",
// })
// .then(function (message) {
// alert("mail sent successfully")
// });
// }
<script src="https://smtpjs.com/v3/smtp.js"></script>
<div class="form-container">
<h1>Loan Application Form</h1>
<form id="myForm" method="post" action="thankyou.html">
<div class="formdesign" id="name">
Full Name:<input type="text" class="form-control" placeholder="Enter your fullname" name="fullName"><span class="formerror"></span>
</div>
<div class="formdesign" id="email">
Email:<input type="email" class="form-control" placeholder="Enter email" name="email"><span class="formerror"></span>
</div>
<div class="formdesign" id="panno">
PAN No:<input type="text" class="form-control" placeholder="Like BBHPM5672K" name="pan" maxlength="10"><span class="formerror"></span>
</div>
<div class="formdesign" id="lamount">
Loan Amount:<input type="number" class="form-control" placeholder="Enter loan amount" name="flamnt"><span class="formerror"></span>
</div>
<div class="formdesign">
Enter Captcha:<input type="text" placeholder="enter captcha" class="form-control" id="input_val" />
<p id="operation"><span id="num1">1</span> + <span id="num2">2</span></p>
<button id="bttn" class="captcha-refresh"><i class="fa fa-refresh"></i>Refresh</button>
</div>
<input id="btn" class="button" type="submit" value="Submit">
<input class="button" type="reset" value="Reset">
</form>

Why the data is still updating even the textbox is empty? (Vue 2/Axios/PHP)

Good day everyone! When I enter the customer_address it updates the database even if I have not yet input the customer_first_name, customer_last_name and customer_contact_no. But if I don't input the address he won't update the row in the database. What do you think is the problem? How can I prevent the input from being empty.
//customer.js
identifyCustomerId : function(customer_id) {
for(var index = 0; index < this.customers.length; index++) {
if(customer_id == this.customers[index].customer_id) {
this.customer_first_name = this.customers[index].first_name;
this.customer_last_name = this.customers[index].last_name;
this.customer_contact_no = this.customers[index].contact_no;
this.customer_address = this.customers[index].address;
}
}
},
openToggleUpdateForm : function(customer_id) {
this.updateForm = true;
this.toggleButton = false;
this.customer_id = customer_id;
this.identifyCustomerId(customer_id);
},
userValidation : function() {
if(this.customer_first_name.trim() === "") {
this.first_name_error = true;
this.first_name_error_message = "This field is required!";
console.log(this.first_name_error);
}
else {
this.first_name_error = false;
this.first_name_error_message = "";
}
if(this.customer_last_name.trim() == "") {
this.last_name_error = true;
this.last_name_error_message = "This field is required!";
}
else {
this.last_name_error = false;
this.last_name_error_message = "";
}
if(this.customer_contact_no.trim() == "") {
this.contact_no_error = true;
this.contact_no_error_message = "This field is required!";
}
else {
this.contact_no_error = false;
this.contact_no_error_message = "";
}
if(this.customer_address.trim() == "") {
this.address_error = true;
this.address_error_message = "This field is required!";
}
else {
this.address_error = false;
this.address_error_message = "";
}
},
updateCustomer : function() {
this.userValidation();
console.log(this.customer_first_name);
axios.post(this.urlRoot + this.api + "update_customer.php", {
customer_id : this.customer_id,
first_name : this.customer_first_name,
last_name : this.customer_last_name,
contact_no : this.customer_contact_no,
address : this.customer_address
}).then(function (response) {
if(response.data.status == "NOT OK") {
vm.first_name_error = response.data.first_name_error;
vm.last_name_error = response.data.last_name_error;
vm.contact_no_error = response.data.contact_no_error;
vm.address_error = response.data.address_error;
} else{
console.log(response);
vm.retrieveCustomer();
}
});
}
//update_customer.php (api)
$customer = new Customer();
$data = json_decode(file_get_contents("php://input"),true);
$response = [];
$response['status'] = "OK";
if(empty($data['customer_id'])) {
$response['customer_id_error'] = true;
$response['status'] = "NOT OK";
}
if(empty($data['first_name'])) {
$response['first_name_error'] = true;
$response['status'] = "NOT OK";
echo $data['first_name'];
}
if(empty($data['last_name'])) {
$response['last_name_error'] = true;
$response['status'] = "NOT OK";
}
if(empty($data["contact_no"])) {
$response["contact_no_error"] = true;
$response["status"] = "NOT OK";
}
if(empty($data['address'])) {
$response['address_error'] = true;
$response['status'] = "NOT OK";
}
else{
$customer = new Customer();
$response['status'] = "OK";
echo json_encode($response);
$customer->customer_id = ucwords($data['customer_id']);
$customer->first_name = ucwords($data['first_name']);
$customer->last_name = ucwords($data['last_name']);
$customer->contact_no = $data['contact_no'];
$customer->address = ucwords($data['address']);
$customer->updateCustomer();
}
//Customer.php
public function updateCustomer() {
$sql= "UPDATE tbl_customer SET customer_id = :customer_id, first_name = :first_name,
last_name = :last_name, contact_no = :contact_no,
address = :address WHERE customer_id = :customer_id";
$stmt = $this->connection->prepare($sql);
return $stmt->execute([
":customer_id" => $this->customer_id,
":first_name" => $this->first_name,
":last_name" => $this->last_name,
":contact_no" => $this->contact_no,
":address" => $this->address
]);
}
//customer_page.php ("update button on my table")
<button class="btn btn-secondary" #click="openToggleUpdateForm(customer.customer_id)">Update</button>
//customer_page.php ("update form")
<div class="add-content" v-if="updateForm">
<h1>Add Customer</h1>
<label>Firstname: </label>
<input type="text" name="first_name" :class="{ invalid : first_name_error }" v-model="customer_first_name" required><br>
<div class="text-danger">{{ first_name_error_message }}</div>
<label>Lastname: </label>
<input type="text" name="last_name" :class="{ invalid : last_name_error }" v-model="customer_last_name" required><br>
<div class="text-danger">{{ last_name_error_message }}</div>
<label>Contact no.: </label>
<input type="text" name="contact_no" :class="{ invalid : contact_no_error }" v-model="customer_contact_no" required><br>
<div class="text-danger">{{ contact_no_error_message }}</div>
<label>Address: </label>
<input type="text" name="address" :class="{ invalid : address_error }" v-model="customer_address" required><br>
<div class="text-danger">{{ address_error_message }}</div>
<div class="mt-4">
<button #click="updateCustomer()" class="btn btn-primary">Add</button>
</div>
</div>

validating using onblur and onsubmit

I would like to know how to validate a form when I use the onblur handler and the onsubmit handler at the same time. I've tried to do it and it goes straight to the submit page without displaying an error message.
Because I also have radio buttons and checkboxes, how do I validate these if the user didn't click the radio button and exclude the checkbox from validation.
Thank You
function IsNotBlank(tf, tfHelp) {
var value = tf.value;
if (value == " ") {
tf.className = "invalid ";
tfHelp.innerHTML = "This field can 't be blank.";
return false;
} else {
tf.className = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckLetters(tf, tfHelp) {
//check empty field from previous function.
var NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false) {
return false;
}
//assign field value
var value = tf.value;
//check if there is numbers.
var regex = new RegExp(/^[A-Za-z]{5,18}$/);
var testResult = regex.test(value);
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Use letters only and lengths must be between 5 and 18 characters.";
return false;
} else {
tf.className = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckPhNumber(tf, tfHelp) {
//check empty field
var NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false)
return false;
var value = tf.value;
//validate phone number.
var regex = /^\d{8,10}$/;
var testResult = regex.test(value);
//logic
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Please enter a valid phone number.";
return false;
} else {
tf.ClassName = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckEmail(tf, tfHelp) {
//check empty field
NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false) {
return false;
}
var value = tf.value;
//validate email address
var regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var testResult = regex.test(value);
//logic
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Please enter a valid email address.";
return false;
} else {
tf.className = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckPostCode(tf, tfHelp) {
//check empty field
var NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false)
return false;
var value = tf.value;
//validate postcode.
var regex = /^\d{4}$/;
var testResult = regex.test(value);
//logic
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Please enter a 4 digit post code.";
return false;
} else {
tf.ClassName = "valid";
tfHelp.innerHTML = "";
return false;
}
}
function ValidateForm(form) {
var formCheck = true;
for (var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
//alert(form.elements[i]);
if (e.onblur) {
// alert(e.onblur());
formCheck = e.onblur() && formCheck;
}
}
return formCheck;
}
function ResetForm(form) {
//select input elements and change color back to default
var arrayInputs = document.getElementsByTagName("input");
for (var i = 0; i < arrayInputs.length; i++) {
arrayInputs[i].className = "valid";
}
//clear text on span elements
var arraySpans = document.getElementsByTagName('span ');
for (var i = 0; i < arraySpans.length; i++) {
arraySpans[i].innerHTML = "";
}
}
<form action="submit.html" onreset="ResetForm()" onsubmit="ValidateForm(this);">
<div>
<label for="fname" class="label">First Name:</label>
<input class="valid" type="text" id="txtFname" onblur="return CheckLetters(this, txtFnameHelp);" />
<span id="txtFnameHelp"></span>
</div>
<div class="one">
<label for="lname" class="label">Last Name:</label>
<input class="valid" name="lname" id="txtLname" type="text" onblur="return CheckLetters(this, txtLnameHelp);" />
<span id="txtLnameHelp"></span>
</div>
<div class="one">
<label class="label" for="phone">Phone Number:</label>
<input class="one" id="txtPhone" type="text" onblur="CheckPhNumber(this, txtPhoneHelp);"><br>
<span id="txtPhoneHelp"></span>
</div>
<div class="one">
<label for="email" class="label">Email Address:</label>
<input class="valid" id="txtEmail" type="text" onblur="CheckEmail(this, txtEmailHelp)">
<span id="txtEmailHelp"></span><br>
</div>
<div class="one">
<label class="label">Post Code:</label>
<input id="txtPostcode" type="text" onblur="CheckPostCode(this, txtPostCodeHelp);"> <br>
<span id="txtPostCodeHelp"></span>
</div>
<br>
<div>
<label>Prefered Contact Method</label><br>
</div>
<div class="one">
</--<input type="radio" name="contact" value="email">Email
</-- <input type="radio" name="contact" value="phone">Phone
</div>
<br>
<div class="one">
<label>Your Message:</label><br />
<textarea id="txtMessage" rows="8" cols="40" onblur="IsNotBlank(this, txtMessageHelp)">Your Message</textarea>
<span id="txtMessageHelp"></span>
<br><br>
</div>
</--<input class="one" type="checkbox" name="newsletter" value="subscribe">I would like to subscribe to the newsletter <br>
<div>
<input class="one" type="submit" value="Send">
<input class="one " type="Reset " value="Clear">
<br><br>
</div>
</form>
Note that these type of JavaScript code can only be debugged using Microsoft Visual Studio for some reason and would not work on using legacy text editors.
You can use below concept to perform the both action and use window.addEventListener('DOMContentLoaded'function(e) {}) to check the validation
var error_user_name = false;
function checkpw(ele, e){
var user_name = document.forms["joinform"]["user_name"].value;
if (user_name == null || user_name == "") {
text = "UserName : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_name = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_name = true;
}
}
function submitall(ele, e) {
checkpw();
if(error_user_name == false) {
e.preventDefault();
} else {
console.log('form submitted');
}
}
window.addEventListener('DOMContentLoaded', function(e) { document.getElementById('user_name').addEventListener('blur', function(e) {
checkpw(this, e);
setTimeout(function() {
if (document.activeElement.id == 'join') {
document.activeElement.click();
}
}, 10);
}, false);
document.getElementById('joinform').addEventListener('submit', function(e) {
submitall(this, e);
}, false);
});
<form id="joinform" method="post" name="joinform" action="#hello">
<h2>Join</h2>
<input type="text" name="user_name" id="user_name" placeholder="User_Name"/>
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>

inherit function that is inside scope to another function

I want to get the return value of validatePassword() and validate() function outside its scope. Those values should be returned inside the function firstNextButton(). If both input fields are validated right, the button must be clickable, which means that the attribute disabled will be removed inside the element.
(function validationPassword() {
var inputPassWord = document.getElementById('inputpassword');
var passErrorMessage = document.getElementById('password-error');
function validatePassword() {
var inputPasswordValue = inputPassWord.value;
if(inputPasswordValue.length > 0) {
passErrorMessage.innerHTML = "Password correct";
} else {
passErrorMessage.innerHTML = "Password incorrect";
}
}
inputPassWord.onblur = function() {
firstNextButton();
}
})();
(function validationEmail() {
var emailInput = document.getElementById('email');
var emailError = document.getElementById('email-error');
var email = emailInput.value;
function validateEmail(email) {
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(email);
}
function validate() {
if(validateEmail(email)) {
emailError.innerHTML = 'Email is correct';
}
else {
emailError.innerHTML = 'mail not correct. Example: name#gmail.com';
}
return false;
}
emailInput.onblur = function() {
emailvalidate;
firstNextButton();
}
})();
function firstNextButton() {
var firstButton = document.getElementById('firstStepButton');
console.log('hello firstNextButton');
// if(validate() && validatePassword()) {
// console.log('hello world');
// firstButton.removeAttribute('disabled', '');
// } else {
// firstButton.setAttribute('disabled', '');
// }
}
<div class="form-block">
<div class="required-field">
<label class="control-label">Email Address</label>
<input name="email" id="email" class="form-control contact-input" type="email" placeholder="<?= $this->lang->line('application_email_address') ?>" required>
<span id="email-error"></span>
</div>
</div>
<div class="form-block">
<div class="required-field">
<label class="control-label">Password</label>
<input name="password" id="inputpassword" class="form-control contact-input" type="password" placeholder="<?= $this->lang->line('application_password') ?>" required>
<span id="password-error"></span>
</div>
</div>
<div>
<button class="btn btn-info btn-round nextBtn pull-right" id="firstStepButton" type="button">Sign Up</button>
</div>
To solely answer your question, you can return the functions you need like this :
var validationPassword = (function validationPassword() {
var inputPassWord = document.getElementById('inputpassword');
var passErrorMessage = document.getElementById('password-error');
function validatePassword() {
var inputPasswordValue = inputPassWord.value;
if (inputPasswordValue.length > 0) {
passErrorMessage.innerHTML = "Password correct";
} else {
passErrorMessage.innerHTML = "Password incorrect";
}
}
inputPassWord.onblur = function() {
firstNextButton();
}
return {
validatePassword: validatePassword
};
})();
var validationEmail = (function validationEmail() {
var emailInput = document.getElementById('email');
var emailError = document.getElementById('email-error');
var email = emailInput.value;
function validateEmail(email) {
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(email);
}
function validate() {
if (validateEmail(email)) {
emailError.innerHTML = 'Email is correct';
} else {
emailError.innerHTML = 'mail not correct. Example: name#gmail.com';
}
return false;
}
emailInput.onblur = function() {
validate();
firstNextButton();
}
return {
validate: validate
};
})();
function firstNextButton() {
var firstButton = document.getElementById('firstStepButton');
if(validationEmail.validate() && validationPassword.validatePassword()) {
console.log('hello world');
firstButton.removeAttribute('disabled', '');
} else {
firstButton.setAttribute('disabled', '');
}
}
<div class="form-block">
<div class="required-field">
<label class="control-label">Email Address</label>
<input name="email" id="email" class="form-control contact-input" type="email" placeholder="<?= $this->lang->line('application_email_address') ?>" required>
<span id="email-error"></span>
</div>
</div>
<div class="form-block">
<div class="required-field">
<label class="control-label">Password</label>
<input name="password" id="inputpassword" class="form-control contact-input" type="password" placeholder="<?= $this->lang->line('application_password') ?>" required>
<span id="password-error"></span>
</div>
</div>
<div>
<button class="btn btn-info btn-round nextBtn pull-right" id="firstStepButton" type="button">Sign Up</button>
</div>
Or refactor your code and take them outside the modules scopes.
As a side note, you forgot the parenthesis in emailInput.onblur function (and gave it the wrong name, too) :
emailInput.onblur = function() {
validate(); // <---- Here
firstNextButton();
}
Also, you don't call validePassword inside the onblur event, and you don't take the value of the input you're trying to validate. Add something like email = emailInput.value; inside the top of the validate function.

.focus() after submit incorrect infos to a form, doesn't work

I have an easy form. When i submit the form with incorrect informations, the error message appear but i would that the first incorrect input is highlight with focus.
I think how i use .focus() is right but it might doesn't fit with the rest of the function.
Here my code:
<form name="login-registration" onSubmit="return validateForm()" method="post" action="" novalidate >
<div class="span-4">
<label>Email</label>
<label>Your password</label>
<label>Repeat password</label>
<label> <input class="inline check" type="checkbox" id="policy" name="policy" value="policy" /> I agree</label>
</div>
<div class="span-4">
<input type="email" name="emailinput" id="emailinput" value = "<?php echo htmlspecialchars($_POST['emailinput']); ?>"/>
<input type="password" name="pswinput" id="pswinput" value=""/>
<input type="password" name="pswrepeatinput" id="pswrepeatinput" value="" onblur="isValidPswRep()"/>
<input type="submit" name="submit" value="Login" />
</div>
<div class="span-4">
<p id="emptyEmail" class="hidden">Email field is required</p>
<p id="invalidEmail" class="hidden">Email you insert is invalid!</p>
<p id="pswMinMax" class="hidden">Password should be from 4 to 8 caracters</p>
<p id="pswLettNum" class="hidden">Password should be letters and numbers. No special caracters are allow</p>
<p id="pswR" class="hidden">Your passwords is different</p>
<p id="checkN" class="hidden">You must agree to our term</p>
</div>
</form>
And here the script:
function validateForm(){
var email = document.getElementById("emailinput").value;
var psw = document.getElementById("pswinput").value;
var pswrep = document.getElementById("pswrepeatinput").value;
var check = document.getElementById("policy");
if (isValidEmail(email)){
if(isValidPsw(psw,4,8)){
if(isValidPswRep(pswrep)){
if(isValidCheckbox(check)){
return true;
}
}
}
}
return false;
}
function isValidEmail(email) {
var validCharacters = /^\w+#\w+\.\w+$/;
if(email == ""){
var emailErr = document.getElementById("emptyEmail");
emailErr.className = "error";
var emailErr2 = document.getElementById("invalidEmail");
emailErr2.className = "hidden";
return false;
email.focus();
} else if(!validCharacters.test(email)) {
var emailErr = document.getElementById("emptyEmail");
emailErr.className = "hidden";
var emailErr2 = document.getElementById("invalidEmail");
emailErr2.className = "error";
return false;
email.focus();
} else {
var emailErr = document.getElementById("emptyEmail");
emailErr.className = "hidden";
var emailErr2 = document.getElementById("invalidEmail");
emailErr2.className = "hidden";
return true;
}
}
function isValidPsw(psw, minLen, maxLen) {
var lengthPsw = psw.length;
var lettNum = /^[0-9a-zA-Z]+$/;
if(lengthPsw == 0 || lengthPsw <= minLen || lengthPsw > maxLen){
var pswErr = document.getElementById("pswMinMax");
pswErr.className = "error";
var pswErr2 = document.getElementById("pswLettNum");
pswErr2.className = "hidden";
return false;
psw.focus();
} else if(!lettNum.test(psw)){
var pswErr2 = document.getElementById("pswLettNum");
pswErr2.className = "error";
var pswErr = document.getElementById("pswMinMax");
pswErr.className = "error";
return false;
psw.focus();
} else {
var pswErr = document.getElementById("pswMinMax");
pswErr.className = "hidden";
var pswErr2 = document.getElementById("pswLettNum");
pswErr2.className = "hidden";
return true;
}
}
function isValidPswRep(pswrep){
var psw = document.getElementById("pswinput").value;
var pswrep = document.getElementById("pswrepeatinput").value;
if(pswrep != psw){
var pswRepErr = document.getElementById("pswR");
pswRepErr.className = "error";
return false;
pswrep.focus();
}
var pswRepErr = document.getElementById("pswR");
pswRepErr.className = "hidden";
return true;
}
function isValidCheckbox(check){
if (!check.checked){
var checkErr = document.getElementById("checkN");
checkErr.className = "error";
return false;
check.focus();
}
var checkErr = document.getElementById("checkN");
checkErr.className = "hidden";
return true;
}

Categories