Form Fields Validation Through Javascript - javascript

I'm making a form and i want when the fields are empty the border of the fields gets red but my code is not working please help ! i'm using bootstrap and jquery framework
MY JQUERY
$('document').ready(function() {
$("#form").submit(function() {
var username = $("#username").val();
var email = $("#email").val();
var password = $("#password").val();
var confPassword = $("#confPassword").val();
var message = $("#warning");
if (username == "" && email == "" && password == "" && confPassword == "") {
return false;
$("#username").css("border", "1px solid red");
} else {
return true;
}
});
});

return after setting the css rule. Once the return statement is executed none of the statement after it in the function is executed because the control flow is returned to the caller by the return call.
$('document').ready(function () {
$("#form").submit(function () {
var username = $("#username").val();
var email = $("#email").val();
var password = $("#password").val();
var confPassword = $("#confPassword").val();
var message = $("#warning");
if (username == "" && email == "" && password == "" && confPassword == "") {
$("#username").css("border", "1px solid red");
return false;//return after setting the properties
} else {
return true;
}
});
});

Use OR || to check if user has entered text.
if (username == "" || email == "" || password == "" || confPassword == "" || password != confPassword) {

Adding to avoe answer try code so you should not have to write line of code for each text box,
var isvalid = true;
$("#username, #email, #password, #confPassword, #warning").each(
function()
{
if($(this).val()==="")
{
$(this).css("border", "1px solid red");
isvalid = false;
}
}
);
return isvalid;

Related

javascript validation not reading other conditions on my if else if

what could be wrong I tried to validate the input fields name, company_name, password, when I'm on the password field it says password should not be empty but I already inputted some characters on the password input field.
it doesn't seem to read the validation for password.length and password != confirm_password condition on my else if
here's my code
$('#button-parent a').bind('click',function(e){
var $this = $(this);
var prev = current;
var name = document.getElementById('name').value;
var company_name = document.getElementById('company_name').value;
var password = document.getElementById('password').value;
var confirm_password = document.getElementById('confirm_password').value;
var email = document.getElementById('email').value;
if( name == null || name == "") {
alert('name is required');
return false;
} else if( name.length < 5) {
alert('name must be atleast 6 characters');
return false;
} else if( company_name == null || company_name == ""){
alert('company name is required');
return false;
} else if ( password == null || password == ""){
alert('password field should not be empty');
return false;
} else if ( password.length < 8 ) {
alert('password must be atleast 8 characters');
return false;
} else if ( password != confirm_password ) {
alert('Password do not match');
return false;
}
rIf you are using jQuery why don't you get the values from $() selector?
$(function() {
$('#button-parent a').bind('click', function(e) {
var $this = $(this);
var prev = current;
var name = $('#name').val();
var company_name = $('#company_name').val();
var password = $('#password').val();
var confirm_password = $('#confirm_password').val();
var email = $('#email').val();
var errorMsg = '';
if (name == null || name == "") {
errorMsg += 'name is required\n';
}
if (name.length < 5) {
errorMsg += 'name must be atleast 6 characters\n';
}
if (company_name == null || company_name == "") {
errorMsg += 'company name is required\n';
}
if (password == null || password == "") {
errorMsg += 'password field should not be empty\n';
}
if (password.length < 8) {
errorMsg += 'password must be atleast 8 characters\n';
}
if (password != confirm_password) {
errorMsg += 'Password do not match';
}
if (errorMsg != '') {
alert(errorMsg);
return false;
}
});
});
This way you can show all the errors in the form at once and the users will not be irritated at all.
You can try to use the following line of code instead since you are using jQuery.
var password = $('#password').val();
For a quick check to see if this line works, you can type and run this command at the console section of the developer tool. If it works you should be seeing the input value.

How to stop form from submitting after failing validation.

I've been working on this form and have come to a roadblock. I'm trying to stop the form from submitting if it fails validation. The form itself is using formspree.io to collect the results and email them. I set out to write this in all js.
I think that because of this adding return false to the end of any validation does not work because formspree is doing something extra that I am not aware of/ don't understand.
Here is my code without the form elements but just validation logic and submit button. You can look at all the code for the form here.Any help or hints or direction would be appreciated thanks.
var app = document.createElement('form');
app.name = 'formIT'
app.action = "https://formspree.io/alaw989#gmail.com"
app.method = "POST"
//all div elements and stuff used to build the form would be here//
var submit = document.createElement('button');
submit.textContent = 'Submit'
app.appendChild(submit)
submit.style.cssText = "display: block; margin: 40px 0px 0px 20px; background-color: #1DA2F5; border: none; color: white; padding: 16px 32px; text-decoration: none; cursor: pointer;"
submit.type = "submit"
submit.value = "Send"
submit.addEventListener('click', function() {
var x = emailInput.value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
}
var yes1 = radio1a.checked;
var no1 = radio1b.checked;
if (yes1 == "" && no1 == "") {
alert("Please answer question 1")
}
var yes2 = radio2a.checked;
var no2 = radio2b.checked;
if (yes2 == "" && no2 == "") {
alert("Please answer question 2")
}
var yes3 = radio3a.checked;
var no3 = radio3b.checked;
if (yes3 == "" && no3 == "") {
alert("Please answer question 3")
}
var yes4 = radio4a.checked;
var no4 = radio4b.checked;
if (yes4 == "" && no4 == "") {
alert("Please answer question 4")
}
var yes5 = radio5a.checked;
var no5 = radio5b.checked;
if (yes5 == "" && no5 == "") {
alert("Please answer question 5")
}
var yes6 = radio6a.checked;
var no6 = radio6b.checked;
if (yes6 == "" && no6 == "") {
alert("Please answer question 6")
}
var a = input1.value
var b = input2.value
if (a === "") {
alert("Missing Question 7")
}
if (b === "") {
alert("Missing Question 8")
}
});
For your question, I would recommend using an error-catching function or similar, which would kill the script on errors.
Check out the answer: Is it possible to stop JavaScript execution?
Try
button.addEventListener('click', function() {
var form = document.getElementById('form-id');
event.preventDefault();
// validations here
if (validationsPassed) form.submit()
});
First of all, your radio button "checked" events should be checking for true/false not " ". Second, you have two options. You could add e in your click event and add e.preventDefault() as Matias suggested:
submit.addEventListener('click', function(e) {
e.preventDefault();
}
Or add a function to validate form in your form tag:
<form onsubmit="validateForm();">

Unknown error the true part of if state dosen't work

I've write a code for simple pass and username form that will show up a content if u entered the user and password correct
but it seems like there is a logical error on it that I can't find
function show() {
if (document.getElementById("user").value == "ahmed" && document.getElementById("pass").value == "ahmed") {
document.getElementById("content").style.visibility = "visible";
document.getElementById("pass1").style.visibility = "hidden";
} else if (document.getElementById("user").value != "ahmed" && document.getElementById("pass").value != "ahmed") {
alert("Password and username is incorrect")
} else if (document.getElementById("pass").value != "ahmed") {
alert("Password is incorrect");
} else if (document.getElementById("user").value != "ahmed") {
alert("Username is incorrect")
}
}
The function work when I entered a wrong pass or username but when I entered them right nothing oth this code , the page just refresh automatically
document.getElementById("content").style.visibility = "visible";
document.getElementById("pass1").style.visibility = "hidden";
source
I created a fiddle and it is working fine
I don't know why it is not working for you. look at the fiddle
https://jsbin.com/vezito/edit?html,js,output
function show() {
var content = document.getElementById("content");
var name = document.getElementById("name");
var pass = document.getElementById("pass");
if (name.value == "ahmed" && pass.value == "ahmed") {
document.getElementById("content").style.visibility = "visible";
document.getElementById("pass").style.visibility = "hidden";
} else if (name.value != "ahmed" && pass.value != "ahmed") {
alert("Password and username is incorrect");
} else if (pass.value != "ahmed") {
alert("Password is incorrect");
} else if (name.value != "ahmed") {
alert("Username is incorrect");
}
}

Validating using JavaScript - how to show to all validation error message's

I have function that checks if fields are blank but if all fields are blank it only shows one of the validation message's, I think this is because I have used an if statement:
function validateForm()
{
var sName=document.forms["myForm"]["surname_5"].value;
if (sName==null || sName=="")
{
document.getElementById("sNameMessage").innerHTML = "*Surname is required";
return false;
}
var x=document.forms["myForm"]["firstname_4"].value;
if (x==null || x=="")
{
document.getElementById("fNameMessage").innerHTML = "*First name is required";
return false;
}
var y=document.forms["myForm"]["selectid"];
if(y.options[y.selectedIndex].value == "Title")
{
document.getElementById("titleMessage").innerHTML = "You need to select a title";
return false;
}
}
How do I get it so all validation messages show if the user has left all fields blank?
Don't return false immediately. Set a variable to false (after defining it as true at the very start of the function) and return that variable at the end.
Try something like this (or add all your code if you need more details)
JavaScript:
function validateForm() {
var sName = document.forms["myForm"]["surname_5"].value;
var ret = true;
if (sName == null || sName == "") {
document.getElementById("sNameMessage").innerHTML = "*Surname is required";
ret = false;
}
var x = document.forms["myForm"]["firstname_4"].value;
if (x == null || x == "") {
document.getElementById("fNameMessage").innerHTML = "*First name is required";
ret = false;
}
var y = document.forms["myForm"]["selectid"];
if (y.options[y.selectedIndex].value == "Title") {
document.getElementById("titleMessage").innerHTML = "You need to select a title";
ret = false;
}
return ret;
}

Form submitting wrongfully

I am using a script to validate a few form fields before the form is submitted. The script is supposed to return false if the validations failed. On linux the script works fine in FF, Chrome and Opera. On windows the script fails and the forms is submitted on Chrome, Safari and IE.
Your thoughtswill be appreciated.
$(document).ready(function(){
// Place ID's of all required fields in the array.
required=["formname","formemail"];
email = $("#formemail");
name = $("#formname");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
$("#suggestionform").submit( function(){
//validate required fields
for(i = 0; i < required.length; i++){
var input = $('#'+required[i]);
if( (input.val() == "") || (input.val() == emptyerror)){
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
}else {
input.removeClass("needsfilled");
}
}
if( !/^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())){
email.addClass("needsfilled");
email.val(emailerror);
}
if ( "" == name.val()){
name.addClass("needsfilled");
name.val(emptyerror);
}
if( $("#link1").val() + $("#link2").val() + $("#link3").val() + $("#link4").val() + $("#textarea1").val() + $("#textarea2").val() == "") {
errornotice.fadeIn(750);
alert("returning fail")
return false;
}
if( $(":input").hasClass("needsfilled")){
alert("returning fail here")
return false;
}else{errornotice.hide();return true;}
});
$(":input").focus( function(){
if ($(this).hasClass("needsfilled")){
$(this).val("");
$(this).removeClass("needsfilled");
}
})
});
Version 2
var required=["formname","formemail"];
var email = $("#formemail");
var name = $("#formname");
var errornotice = $("#error");
// The text to show up within a field when it is incorrect
var emptyerror = "Please fill out this field.";
var emailerror = "Please enter a valid e-mail.";
function suggestionSubmit(theform){
required=["formname","formemail"];
email = $("#formemail");
name = $("#formname");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
for(i = 0; i < required.length; i++){
var input = $('#'+required[i]);
if( (input.val() == "") || (input.val() == emptyerror)){
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
}else {
input.removeClass("needsfilled");
}
}
if( !/^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())){
email.addClass("needsfilled");
email.val(emailerror);
}
if ( "" == name.val()){
name.addClass("needsfilled");
name.val(emptyerror);
}
if( $("#link1").val() + $("#link2").val() + $("#link3").val() + $("#link4").val() + $("#textarea1").val() + $("#textarea2").val() == "") {
errornotice.fadeIn(750);
return false
}
if( $(":input").hasClass("needsfilled")){
return false;
}
else{errornotice.hide();return true;}
}
You can try to write smth like that
$(document).ready(function(){
// Place ID's of all required fields in the array.
required=["formname","formemail"];
email = $("#formemail");
name = $("#formname");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
$("#suggestionform").submit( function(event){
//validate required fields
for(i = 0; i < required.length; i++){
var input = $('#'+required[i]);
if( (input.val() == "") || (input.val() == emptyerror)){
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
}else {
input.removeClass("needsfilled");
}
}
if( !/^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())){
email.addClass("needsfilled");
email.val(emailerror);
}
if ( "" == name.val()){
name.addClass("needsfilled");
name.val(emptyerror);
}
if( $("#link1").val() + $("#link2").val() + $("#link3").val() + $("#link4").val() + $("#textarea1").val() + $("#textarea2").val() == "") {
errornotice.fadeIn(750);
alert("returning fail")
event.preventDefault();
return false;
}
if( $(":input").hasClass("needsfilled")){
alert("returning fail here")
event.preventDefault();
return false;
}else{errornotice.hide();return true;}
});
Hope it helps.

Categories

Resources