I am trying to do few validations in a form and it is not up to the mark. I need to hide the error message message of the name and show only email error. But it is not happening. Maybe you will understand from the code.
Here it is.
function validateform(form){
event.preventDefault();
console.log(form);
var i;
var fname = form.name.value;
var email = form.email.value;
var message = form.getElementsByClassName("error-message");
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (fname==null || fname==""){
for (i = 0; i < message.length;i++)
{
form.getElementsByClassName("error-message")[i].innerHTML="Please Enter Name";
return false;
}
}
else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {
for (i = 0; i < message.length;i++)
{
form.getElementsByClassName("error-email")[i].innerHTML="The email address you've entered contains an incorrect character. Please check this information and try again.";
return false;
}
}
else if (fname!=null || fname!=""){
for (i = 0; i < message.length;i++)
{
form.getElementsByClassName("error-message")[i].style.display = "none";
return false;
}
}
HTML
<form name="ccform" method="post" onsubmit="validateform(this)">
<p class="customer-name">Name</p>
<input type="text" class="input-name" name="name"></input>
<p class="error-message"></p>
<p class="customer-name">Email</p>
<input type="text" class="input-name" name="email" placeholder="e.g. name#emailaddress.com"></input>
<p class="error-email"></p>
<button type="submit" class="submit-button">Submit</button>
</form>
I want to hide error-message and show only error-email when name is entered,email is not entered and i press submit button.
P.S: Please no jQuery.
You have trying to hide error_message class in an else if condition. The code will not parse through all the if conditions. In your case, you want to show the email validation message and hence it will enter the second condition and will not enter the third condition. Refer the usage of if-else if-else statement here. You just try to merge the second and third condition together as follows.
if (fname==null || fname==""){
for (i = 0; i < message.length;i++)
{
form.getElementsByClassName("error-message")[i].innerHTML="Please Enter Name";
form.getElementsByClassName("error-message")[i].style.display = "block";
return false;
}
} else {
form.getElementsByClassName("error-message")[i].style.display = "none";
}
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {
for (i = 0; i < message.length;i++)
{
form.getElementsByClassName("error-email")[i].innerHTML="The email address you've entered contains an incorrect character. Please check this information and try again.";
form.getElementsByClassName("error-email")[i].style.display = "block";
return false;
}
} else {
form.getElementsByClassName("error-email")[i].style.display = "none";
}
Hope it helps.
This is what worked for me.
function validateform(form){
var i;
var fname = form.name.value;
var email = form.email.value;
var message = form.getElementsByClassName("error-message");
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (fname==null || fname==""){
for (i = 0; i < message.length;i++)
{
form.getElementsByClassName("error-message")[i].innerHTML="Please enter your name";
form.getElementsByClassName("error-message")[i].style.display = "block";
form.getElementsByClassName("error-email")[i].style.display = "none";
return false;
}
}
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {
for (i = 0; i < message.length;i++)
{
form.getElementsByClassName("error-email")[i].innerHTML="The email address you've entered contains an incorrect character. Please check this information and try again.";
form.getElementsByClassName("error-message")[i].style.display = "none";
form.getElementsByClassName("error-email")[i].style.display = "block";
return false;
}
}
Related
I have a multistep form needs additional validation for password, email, credit card expiry date.
As there is a function validateForm I want to add to this so that it also checks the password has 8 char and email is valid ('#').
The main issue is the for loop that says input is valid/invalid before allowing user to go to next step in form. At the moment it just checks if there is anything in each box, if so it goes next page. I need it to also check that the password/email is valid as per above requests.
var currentTab = 0;
showTab(currentTab);
function showTab(n) { /*need to add in password/email validation to below but unsure how */
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("nextBtn").innerHTML = "Complete Order";
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
fixStepIndicator(n)
}
function nextPrev(n) {
var x = document.getElementsByClassName("tab");
if (n == 1 && !validateForm()) return false;
x[currentTab].style.display = "none";
currentTab = currentTab + n;
if (currentTab >= x.length) {
document.getElementById("orderForm").submit();
return false;
}
showTab(currentTab);
}
function validateForm() {
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
for (i = 0; i < y.length; i++) {
if (y[i].value == "") {
y[i].className += "invalid";
valid = false;
}
}
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid;
}
Assuming you can edit the HTML elements and add id's to the input fields, you can simply use document.getElementById to get each specific input.
<html>
<body>
<input type="password" id="myPassword" />
<input type="email" id="myEmail" />
</body>
</html>
function validateForm() {
const pwInput = document.getElementById('myPassword');
if( pwInput && pwInput.value.length < 5) {
console.log('password not valid');
}
const emailInput = document.getElementById('myEmail');
if(emailInput && emailInput.search(/#/) === -1) {
console.log('email not valid');
}
}
This sounds like homework, so this is some additional food for thought for production code.
While doing password validation on the client side is okay, server side must absolutely do password validation.
Email validation is very tricky to do. You can use a regex you find, but even the ones on Stack Overflow are filled with caveats and test cases that don't work. For production code, using a library along with email verification is your best bet.
I want the form to not be submitted when the inputs are wrong. The error messages do appear but my form still gets submitted nonetheless. I cant seem to find the problem would appreciate the help thank you :)-----------------------------------------------------------------------------------------------------
<form action="/handleServer.php" method="get" onsubmit="return validateForm()">
<!-- starting with first name-->
<h4 class="heading" >First name:</h4>
<input id="fname" type="text" name="fname" size="30">
<span id="errorName" class="error"></span>
<!-- module code -->
<h4 class="heading">Module code:</h4>
<input id="mcode" type="text" name="mcode" size="30">
<span id="errorCode" class="error"></span>
<input type="submit" value="Submit">
</form>
<script>
//input field using if-else statements
function validateForm() {
var fname = document.getElementById("fname").value;
var mcode = document.getElementById("mcode").value;
var errorN = document.getElementById("errorName");
var errorC = document.getElementById("errorCode");
//test for an empty input
if (fname === '' && mcode === '') {
errorN.innerHTML = "Please fill in the blank";
errorC.innerHTML = "Please fill in the blank";
return false;
}
if (fname === '') {
errorN.innerHTML = "Please fill in the blank";
return false;
} else {
errorN.innerHTML = "";
}
if (mcode === '') {
errorC.innerHTML = "Please fill in the blank";
return false;
} else {
errorC.innerHTML = "";
}
//test for invalid format
if (/^[A-Z]\D{2,30}$/.test(fname) == false) //if its true, it will go to the second input
{
errorN.innerHTML = "One capital letter and no digits allowed";
fname.style.color="red";
return false;
} else {
fname.innerHTML = "";
}
if (/^[a-z]{3}[1-9]\d{4}$/.test(mcode) == false)
{
errorC.innerHTML = "Wrong format";
mcode.style.color="red";
return false;
} else {
mcode.innerHTML = "";
}
return true; }
The problem seems to be these four lines of code:
fname.style.color="red";
fname.innerHTML = "";
mname.style.color="red";
mname.innerHTML = "";
fname and mname are strings, therfore fname.style and mname.style both result in undefined. Obviously you can't set properties on undefined which is why you are getting an error.
//You are getting the value properties which are strings:
var fname = document.getElementById("fname").value;
var mcode = document.getElementById("mcode").value;
The error is stopping your code before you can return false, preventing the cancelation of the form submit.
The solution is to instead make two more variables storing the actual input elements:
var finput = document.getElementById("fname");
var minput = document.getElementById("mname");
Then change lines:
fname.style.color="red";
fname.innerHTML = "";
mname.style.color="red";
mname.innerHTML = "";
to:
finput.style.color="red";
finput.innerHTML = "";
minput.style.color="red";
minput.innerHTML = "";
Here is a working version:
<form action="/handleServer.php" method="get" onsubmit="return validateForm()">
<!-- starting with first name-->
<h4 class="heading">First name:</h4>
<input id="fname" type="text" name="fname" size="30">
<span id="errorName" class="error"></span>
<!-- module code -->
<h4 class="heading">Module code:</h4>
<input id="mcode" type="text" name="mcode" size="30">
<span id="errorCode" class="error"></span>
<input type="submit" value="Submit">
</form>
<script>
//input field using if-else statements
function validateForm() {
var finput = document.getElementById("fname");
var minput = document.getElementById("mname");
var fname = document.getElementById("fname").value;
var mcode = document.getElementById("mcode").value;
var errorN = document.getElementById("errorName");
var errorC = document.getElementById("errorCode");
//test for an empty input
if (fname === '' && mcode === '') {
errorN.innerHTML = "Please fill in the blank";
errorC.innerHTML = "Please fill in the blank";
return false;
}
if (fname === '') {
errorN.innerHTML = "Please fill in the blank";
return false;
} else {
errorN.innerHTML = "";
}
if (mcode === '') {
errorC.innerHTML = "Please fill in the blank";
return false;
} else {
errorC.innerHTML = "";
}
//test for invalid format
if (/^[A-Z]\D{2,30}$/.test(fname) == false) //if its true, it will go to the second input
{
errorN.innerHTML = "One capital letter and no digits allowed";
finput.style.color = "red";
return false;
} else {
finput.innerHTML = "";
}
if (/^[a-z]{3}[1-9]\d{4}$/.test(mcode) == false) {
errorC.innerHTML = "Wrong format";
minput.style.color = "red";
return false;
} else {
minput.innerHTML = "";
}
return true;
}
</script>
Pass the event to the form validation function
onsubmit="return validateForm(e)"
Then prevent default submission using
e.preventDefault();
Your return statement should be inside a condition. Right now you're existing the condition and ending the function with a return true; regardless of what the conditional statements have already returned. So:
if (fname === '' && mcode === '') {
errorN.innerHTML = "Please fill in the blank";
errorC.innerHTML = "Please fill in the blank";
return false;
}else{
return true; // THIS IS WHERE YOU NEED TO RETURN TRUE
}
I see you're returning false in multiple if statements. You'll need to find a way to unify the conditions so that you have one return only for for either true or false.
I have a form with inputs
Fist name
Last name
Password
Etc
Current my validation works one by one. I would like to integrate them into one pop up box.
Example currently:
All not filled up; upon submission it would pop up First name not filled. I want it to be First name not filled, last name not filled etc
function validateForm() {
var x = document.forms["myForm"]["firstname"].value;
if (x == null || x == "") {
alert("First Name must be filled out");
return false;
}
var x = document.forms["myForm"]["lastname"].value;
if (x == null || x == "") {
alert("Last Name must be filled out");
return false;
}
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.forms["myForm"]["email"].value.search(emailRegEx) == -1) {
alert("Please enter a valid email address.");
return false;
}
var status = false;
var paswordregex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
if (document.forms["myForm"]["password"].value.search(paswordregex) == -1) {
alert("Please enter a at least 8 alphanumeric characters");
return false;
}
var password = document.getElementById("password").value;
var confirmPassword = document.getElementById("confirmpassword").value;
if (password != confirmPassword) {
alert("Passwords do not match.");
return false;
}
var checkb = document.getElementById('checkboxid');
if (checkb.checked != true) {
alert('Agree to privacy agreement must be checked');
} else {
status = true;
}
return status;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
function validateForm() {
var regexEmail = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var regexMinThree = /^[A-Za-z0-9_ ]{3,13}$/;
var userFirstName = $.trim($('.firstName').val());
var userLastName = $.trim($('.lastName').val());
var userEmail = $.trim($('.email').val());
var userPassword = $.trim($('.password').val());
var msg = '';
if(!regexMinThree.test(userFirstName)) {
msg = 'FirstName, ';
} else {
msg = '';
}
if(!regexMinThree.test(userLastName)) {
msg = msg+'LastName, ';
} else {
msg = msg+'';
}
if(!regexEmail.test(userEmail)) {
msg = msg+'Email, ';
} else {
msg = msg+'';
}
if(!regexMinThree.test(userPassword)) {
msg = msg+'Password, ';
} else {
msg = msg+'';
}
if(!regexMinThree.test(userPassword) || !regexEmail.test(userEmail) || !regexMinThree.test(userLastName) || !regexMinThree.test(userFirstName)) {
msg = msg+'not filled correctly.';
alert(msg);
}
}
</script>
<form class="userRegistrationForm" onsubmit="return false;" method="post">
<input type="text" class="firstName" placeholder ="FirstName"/>
<input type="text" class="lastName" placeholder ="LastName"/>
<input type="email" class="email" placeholder ="Email"/>
<input type="password" class="password" placeholder ="Password"/>
<button type="submit" onclick="validateForm()" class="userRegistration">Submit</button>
</form>
Add a flag called error and a string called errorMessage, then in each if statement, if there is an error, make error = true and append error message.
Then when submitted, if error == true, alert errorMessage
You can add an <ul> in your html form where you want to show errors
Example
<ul class="errorContainer"></ul>
Then JS
function validateForm() {
var errors = "";
var x = document.forms["myForm"]["firstname"].value;
if (x == null || x == "") {
errors +="<li>First Name must be filled out</li>";
}
var x = document.forms["myForm"]["lastname"].value;
if (x == null || x == "") {
errors +="<li>Last Name must be filled out</li>";
}
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.forms["myForm"]["email"].value.search(emailRegEx) == -1) {
errors +="<li>Please enter a valid email address.</li>";
}
var status = false;
var paswordregex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
if (document.forms["myForm"]["password"].value.search(paswordregex) == -1) {
errors +="<li>Please enter a at least 8 alphanumeric characters</li>";
}
var password = document.getElementById("password").value;
var confirmPassword = document.getElementById("confirmpassword").value;
if (password != confirmPassword) {
errors +="<li>Passwords do not match.</li>";
}
var checkb = document.getElementById('checkboxid');
if (checkb.checked != true) {
errors +="<li>Agree to privacy agreement must be checked</li>";
}
if(errors!="")
{
$(".errorContainer").html(errors);
return false;
} else {
status = true;
return status;
}
}
I'm trying to validate my form, and the first alert works. But then when the user fills in correct data and clicks submit, the form does not submit anymore. Any help is appreciated, thanks!
<form name="register" action="register.php" onsubmit="return validateForm()" method="post">
// form stuff
function validateForm() {
if (!checkName() || !checkEmail()) {
return false;
} else {
return true;
}
}
function checkName() {
var name=document.forms["register"]["name"].value;
if (name==null || name=="") {
alert("Please fill out your name");
return false;
}
}
function checkEmail() {
var email=document.forms["register"]["email"].value;
var atpos=email.indexOf("#");
var dotpos=email.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {
alert("Not a valid e-mail address");
return false;
}
}
You need checkEmail and checkName to return true when the email or name is present. What you've got now returns undefined.
Here is a fiddle showing the solution and here are the two functions rewritten:
function checkName() {
var name = document.forms["register"]["name"].value;
if (name == null || name == "") {
alert("Please fill out your name");
return false;
}
return true;
}
function checkEmail() {
var email = document.forms["register"]["email"].value;
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
alert("Not a valid e-mail address");
return false;
}
return true;
}
I do ultimately think you'll be happier if you wind up going to jQuery Validation, though.
I'm trying to validate joinUs form
<form id="frmReg" method="post" onsubmit="return valRegs()" action="memb_area/register.php">
//js:
function valRegs(user, pass) {
if (!user || !pass) {
document.getElementById('labInfo').innerHTML = "* White fields required !";
return false;
}
var x = document.forms["frmReg"]["mail"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
document.getElementById('labInfo').innerHTML = "Incorrect mail !";
return false;
}
};
Whichever field is filled or not, whatever is the content of mail field - the result is always: "* White fields required !". What's wrong, please?
The function will never be supplied the user and pass parameters. You will have to find these elements manually in the javascript.
onsubmit="return valRegs()" missed parameters
how are you passing the parameters to the js function. try
function valRegs() {
var user = document.getElementById('user').value;
var pass = document.getElementById('pass').value;
if (!user || !pass) {
document.getElementById('labInfo').innerHTML = "* White fields required !";
return false;
}
};