JavaScript Registration Validation Issues - javascript

everyone! I'm building form validation in HTML/JavaScript. The Problem is that it always behaves like the fields are filled and colors the textboxes in blue.
var fName = document.getElementById('fName').value;
fName = document.getElementById('fName').focus();
var lName = document.getElementById('lName').value;
function validation()
{
//check empty fields
if (fName == "" || lName == "")
{
document.getElementById('fName').style.backgroundColor = "red";
document.getElementById('lName').style.backgroundColor = "red";
}
else(fName != "" || lName != "")
{
document.getElementById('fName').style.backgroundColor = "blue";
document.getElementById('lName').style.backgroundColor = "blue";
}
return false;
}

The problem is the line: fName = document.getElementById('fName').focus(); fName in that line is assigned as undefined so you should try something like:
var element = document.getElementById('fName');
var fName = element.value;
element.focus();
When you fire an event or perform some action for example, the returning value is undefined so fName != "" is true.
E.g.:
console.log(element.classList.add("mystyle")); //return undefined
Also check that you should put else if() instead of else () full example: https://jsfiddle.net/cmq0x2a6/

I suggest you try this:
fname
<input type="text" id="fName" onfocus="checkIfEmpty(event)">
lname
<input type="text" id="lName" onfocus="checkIfEmpty(event)">
<script>
function checkIfEmpty(event) {
if (event.relatedTarget != null) {
if (event.relatedTarget.value.length == 0) {
event.relatedTarget.style.backgroundColor = "red";
} else event.relatedTarget.style.backgroundColor = "green";
}
}
</script>

It looks like the problem is in this typo --
else(fName != "" || lName != "")
{
// set the color to 'blue'
}
You miss the if, so (fName != "" || lName != "") is just an expression that you evaluate and then immediately execute the code inside the curly braces.
It all runs OK because you placed the opening brace on the next line (it would've thrown a SyntaxError otherwise).
You need to change your code to
else if (fName !== "" || lName !== "") {
// set the style
}

Related

Javascript For Loop Not Appending into Div as Expected?

Im not really sure what Im doing wrong here. I essentially check if any of the elements values are empty, and if they are it started to iterate through them.
Once it iterates it appends the id's of the elements that are empty into the div. Or at least thats what I expected it to do. Any help? Thanks!
<script>
function validate(){
var username = document.getElementById("username");
var name = document.getElementById("name");
var phone = document.getElementById("phone-number");
var email = document.getElementById("email");
var password = document.getElementById("password");
var passwordc = document.getElementById("password-confirmation");
var array = [username, name, phone, email, password, passwordc];
if(username.value == "" || name.value == "" || phone.value == "" || email.value == "" || password.value == "" || passwordc.value == ""){
document.getElementById('required-field-error').innerHTML = "The following must not be blank: ";
for(i = 0; i < array.length; i++);{
if(array[i].value == ""){
document.getElementById('required-field-error').innerHTML += " array[i].id ";
}
else{document.getElementById('required-field-error').innerHTML += "";}
}
}
else{
document.getElementById('required-field-error').innerHTML = "";
}
}
</script>
You terminated the for loop independently and hence you are getting out of bond index. And also as pointer by 'Xufox' that is literal string.
Find the corrected script below:
<script>
function validate(){
var username = document.getElementById("username");
var name = document.getElementById("name");
var phone = document.getElementById("phone-number");
var email = document.getElementById("email");
var password = document.getElementById("password");
var passwordc = document.getElementById("password-confirmation");
var array = [username, name, phone, email, password, passwordc];
if(username.value == "" || name.value == "" || phone.value == "" || email.value == "" || password.value == "" || passwordc.value == ""){
document.getElementById('required-field-error').innerHTML = "The following must not be blank: ";
for(i = 0; i < array.length; i++){
if(array[i].value == ""){
document.getElementById('required-field-error').innerHTML += " " + array[i].id;
}
else{document.getElementById('required-field-error').innerHTML += "";}
}
}
else{
document.getElementById('required-field-error').innerHTML = "";
}
}
</script>
You can greatly simplify your code by doing something like this instead:
function validate() {
const requiredFields = ['username', 'name', 'phone-number', 'email', 'password', 'password-confirmation'];
const missingFields = requiredFields.filter(requiredFieldStr => {
return !document.getElementById(requiredFieldStr).value;
});
const requiredFieldError = document.getElementById('required-field-error');
if (missingFields.length > 0) {
requiredFieldError.textContent =
"The following must not be blank: " + missingFields.join('');
} else requiredFieldError.textContent = '';
}
I don't know your requirement exactly.
But if you use JQuery validation that will simplify the things for you.

Form Fields Validation Through 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;

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;
}

alert those textboxes who is still empty

function checkvalue() {
var areaDesc = document.getElementById('areaDesc').value;
var cboLeaveType = document.getElementById('cboLeaveType').value;
var fromDate = document.getElementById('fromDate').value;
var toDate = document.getElementById('toDate').value;
if (areaDesc == "" || fromDate == "" || toDate == "" || cboLeaveType = "")
{
alert("empty hoys");
}
else
{
document.getElementById('hdnAction').value = "go";
document.frmLeave.submit();
}
}
thats the code, it is working but, I want to alert those area who is still empty,
for example.
ex1: areaDesc, fromDate, toDate is not empty, it must alert "txtSignOff still empty";
ex2: areaDesc, fromDate is not empty it must alert "toDate,txtSignOff still empty";
or
toDate is empty
toDate is empty
You can use for in like this:
function checkvalue() {
var fields = {
'areaDesc' : document.getElementById('areaDesc').value;
'cboLeaveType' : document.getElementById('cboLeaveType').value;
'fromDate' : document.getElementById('fromDate').value;
'toDate' : document.getElementById('toDate').value;
};
for(var fieldName in fields){
if(fields[fieldName] == ""){
alert("field" + fieldName + "is empty");
return false;
}
}
document.getElementById('hdnAction').value = "go";
document.frmLeave.submit();
}
You may have to split your if block into individual ones, then use a String and concatenate it with the empty field's name in each if. That is,
var emptyStr = ''
if (areaDesc == '') { emptyStr += 'areaDesc,' ; }
if (fromDate == '') { emptyStr += 'fromDate,' ; }...
...
emptyStr += ' still empty'
if (emptyStr != '') { alert(emptyStr); }
You would have to have an individual if statement for each input type you're requiring, otherwise it's a very generic error message. Something like this should do it:
Also, where is txtSignOff defined? Did you mean cboLeaveType?
If you don't want multiple alerts, just combine all the alerts from the code below and convert them into a string, and then if (error), alert the error string.
function checkvalue() {
var areaDesc = document.getElementById('areaDesc').value;
var cboLeaveType = document.getElementById('cboLeaveType').value;
var fromDate = document.getElementById('fromDate').value;
var toDate = document.getElementById('toDate').value;
if (!areaDesc) alert("areaDesc still empty");
if (!fromDate) alert("fromDate still empty");
if (!toDate) alert("toDate still empty");
if (!txtSignOff) alert("txtSignOff still empty");
if (areaDesc && fromDate && toDate && txtSignOff)
{
document.getElementById('hdnAction').value = "go";
document.frmLeave.submit();
}
}

translate jQuery to pure javascript

I have to fix some form validation but there's no jQuery included in the host page. I'd normally do something like this...
if ($("#contactNameAdd").val() !== '' || $("#contactPhoneAdd").val() !== '') {
$("#contactForm").show()
};
How can I re-write that in normal js?
var name = document.getElementById("contactNameAdd");
var phone = document.getElementById("contactPhoneAdd");
var form = document.getElementById("contactForm");
if(name.value != '' || phone.value != '') {
form.style.display = "block";
}
if (document.getElementById('contactNameAdd').value !== '' || document.getElementById('contactPhoneAdd').value !== '') {
document.getElementById('contactForm').style.display = 'block';
}
In plain javascript, you use document.getElementById('id') to get DOM nodes based on the id attribute. You use .value on a DOM Input element to get its value. And you use .style on any DOM element to set css attributes. In this case "show" means "display: block;".
if (document.getElemenById('contactNameAdd').value != '' || document.getElementById('contactPhoneAdd').value != '') {
document.getElementById('contactForm').style.display = 'block';
}
Try this - checks the 2 values then changes the style.display property of the 'contactForm'
This should do the trick.
var contactNameAdd = document.getElementById("contactNameAdd");
var contactPhoneAdd = document.getElementById("contactPhoneAdd");
if((contactNameAdd !== null && contactNameAdd.value !== '') || (contactPhoneAdd !== null && contactPhoneAdd.value !== ''))
{
document.getElementById("contactForm").style.display = 'block';
}
var contactName = document.getElementById('contactNameAdd');
var contactPhone = document.getElementById('contactPhoneAdd');
if(contactName.value !== '' || contactPhone.value !== '') {
// Different as JQuery, there will be no animation.
// I assume you use 'display:none' to hide the form.
var form = document.getElementById('contactForm');
form.style.display = 'block';
}

Categories

Resources