js syntax passing name elements form validation - javascript

I just need help on how to pass multiple 'name' elements in my function that validates a form submission.
I have this and works fine.
var x = document.forms["myForm"]["FirstName"].value;
if (x == null || x == "")
{
alert("asdf");
return false;
}
tried this but didnt work.
var x = document.forms["myForm"]["FirstName"+"LastName"].value;
if (x == null || x == "")
{
alert("asdf");
return false;
}
Any help with the syntax on how to do so would be appreciated.

What you are trying makes no sense.
var x=document.forms["myForm"]["FirstName"+"LastName"].value;
would get the value from an element called FirstNameLasteName.
So you probably meant this:
var x=document.forms["myForm"]["FirstName"].value + document.forms["myForm"]["LastName"].value;

You meant this:
var x=document.forms["myForm"]["FirstName"].value + " " +
document.forms["myForm"]["LastName"].value;
if (x==null || x=="")
{
alert("asdf");
return false;
}

Related

Check if input fields are filled out in a form

I have a form myForm and I want to check if specific input field are filled out before sending the form. I'm very new to JavaScript so I don't really know what I did wrong. Any help is welcomed.
function validateForm() {
var validate = true;
var alert_string = "";
var children = $("#myForm").children("input");
console.log(children.size());
for(var i = 0; i < children.length ; i++){
if(children[i].attr(id).substring(0,8) != "ABC_FLAT"){
if(children[i].attr(id) == null || children[i].attr(id) == ""){
validate = false;
alert_string = alert_string.concat(childrern[i].attr(id)).concat(", ");
}
}
}
alert_string = alert_string.concat("must be filled out !");
if(validate == false){
alert(alert_string);
return false;
}
return true;
}
children[i].attr(id) == "" // wrong
You don't have to check whether their ids are null, you have to check whether their values are empty :)
if(children[i].value == "")
Since you are already using jQuery, you can simplify that code to a great extent. For example a simple "all fields filled" check can be
var flag=0;
$('#myForm').each(function() {
if ( $(this).val() === '' )
flag=1;
});
if you'll use jQuery, you can check the input fields if empty AND trap also white space/s. Add a class to all input fields , e.g. class="required" and add attribute fieldname with respective value for each input field.
var requiredFields = "";
$("#myForm").find('.required').each(function () {
if ($(this).val().trim().length == 0) {
requiredFields += " - " + $(this).attr("fieldname") + "\n";
}
});
if (requiredFields != "") {
alert("Please enter the following required field(s): \n" + requiredFields);
} else {
//save here
}
You can use required like <input required type="text" name="email" id="log" /> or use jQuery like
$("form").submit(function() {
var has_empty = false;
$(this).find('input').each(function() {
if(! $(this).val()) {
has_empty = true;
return false;
}
});
if(has_empty){return false;}
});

Form validation empty field when checkbox is checked

I'm trying to add validation before form submit. There's an alternative input field, let's call this "Optional" and there's checkboxes "Checkbox1", "Checkbox2", "Checkbox3". When user choose one from this checkboxes, then he must fill input "Optional", if it is empty then he can't submit form and get's some pop-up alert with info to fill this.
I have something like this:
<script>
function validateForm() {
var x = document.forms["form"]["nrumowy"].value;
if (x == null || x == "") {
alert("Numer umowy musi zostać uzupełniony.");
return false;
}
}
</script>
But this input field "nrumowy" must be filled in all situations, so everything okay, and now I want add something similiar but only when one of "Checkbox1", "Checkbox2", "Checkbox3" are checked.
Following code will work instantly while filling the form.
jquery code
<script>
function validateForm() {
var x = document.forms["form"]["nrumowy"].value;
if (x == null || x == "") {
alert("Numer umowy musi zostać uzupełniony.");
return false;
}
var op = document.forms["form"]["optional"].value;
if ($("input[type=checkbox]:checked").length === 0 && op==""){
alert("you must fill Optional field");
return false;
}
}
</script>
If you want to add something similiar but only when one of "Checkbox1", "Checkbox2", "Checkbox3" are checked. Then see if following code helps you.
function validateForm() {
if(document.getElementById("Checkbox1").checked ||
document.getElementById("Checkbox2").checked ||
document.getElementById("Checkbox3").checked ||
{
var x = document.forms["form"]["nrumowy"].value;
if (x == null || x == "") {
alert("Numer umowy musi zostać uzupełniony.");
return false;
}
}
}
You should simply get the values of these checkboxes before that, and if one of them is not checked, exit the function.
function validateForm() {
var frm = document.forms["form"];
if (!frm["Checkbox1"].checked && !frm["Checkbox2"].checked && !frm["Checkbox3"].checked) return;
var x = frm["nrumowy"].value;
if (x == null || x == "") {
alert("Numer umowy musi zostać uzupełniony.");
return false;
}
}
Ok, thanks for your answers, I got now this:
<script>
function validateForm() {
var frm = document.forms["form"];
if (!frm["check_list1"].checked && !frm["check_list2"].checked && !frm["check_list3"].checked) return;
var x = frm["tematyka"].value;
if (x == null || x == "") {
alert("Tematyka artykułu musi zostać uzupełniona.");
return false;
}
}
</script>
<script>
function validateForm2() {
var x2 = document.forms["form"]["nrumowy"].value;
if (x2 == null || x2 == "") {
alert("Numer umowy musi zostać uzupełniony.");
return false;
}
}
</script>
HTML:
<form name="form" method="POST" action="preview.php" onsubmit="return (validateForm() & validateForm2());">
And alerts works, but after user click OK then he goes to preview.php page. When there's only one onsubmit function then this works great, but when I try to combine this two functions then there is a some error.

How to use javascript validating two text areas

The below works, how would i go about including a 2nd "txtArea2"? I've tried joining a & (document.getElementById("txtArea2").value == '') but doesnt work. I'm new to js syntax if someone could help.
if(document.getElementById("txtArea1").value == '')
{
alert("debug");
document.getElementById("txtArea1").style.display ="none";
return false;
};
I'm not sure if I understand your question correctly but you probably want to compare them with || (OR) operator, so if txtArea1 or txtArea2 is empty then the validation shall not pass. That means both textareas will be required fields.
if (document.getElementById("txtArea1").value == '' || document.getElementById("txtArea2").value == '')
{
alert("debug");
document.getElementById("txtArea1").style.display ="none";
return false;
};
Double && specifies the AND condition.
if (document.getElementById("txtArea1").value == '' && document.getElementById("txtArea2").value == '')
If you want to treat both separately, you'll have to use two separate if statements as well. (I outsourced the textareas into variables for readability)
var txtarea1 = document.getElementById("txtArea1");
var txtarea2 = document.getElementById("txtArea2");
if(txtarea1.value == '')
{
alert("debug");
txtarea1.style.display = "none";
return false;
};
if(txtarea2.value == '')
{
alert("debug");
txtarea2.style.display = "none";
return false;
};
If you want to do one thing if either of them (1 or 2) is empty, try this:
if(txtarea1.value == '' || txtarea2.value == '')
{
alert("debug");
txtarea1.style.display ="none";
txtarea2.style.display ="none";
return false;
};
var t1 = document.getElementById("txtArea1").value;
var t2 = document.getElementById("txtArea2").value;
if( t1 == '' || t2 == '')
{
alert("debug");
document.getElementById("txtArea1").style.display ="none";
return false;
};

loop to limit attempts at validation

I am trying to figure out a simple way to limit the amount of attempts on a field(s) through a while loop in javascript. Just doesn't seem to want to loop but the validation is still working. Here is the code I was trying to use:
function validateForm() {
x=document.forms["Form"]["name"].value;
var i=0;
var sum=0;
do {
sum += i;
i++;
}
while (i < 3)
if (x==null || x=="") {
alert("First name must be filled out");
return false;
}
}
Thanks in advance for any ideas.
You will have to store the variable outside of the function:
var numOfTries = 0;
function validateForm() {
if(++numOfTries > 3) {
alert('You have reached the maximum number of tries!');
location.replace("error_page.html"); // do something about it
}
x = document.forms["Form"]["name"].value;
if (x == null || x == "") {
alert("First name must be filled out");
return false;
}

JavaScript Form onkeyup Validation Errors

Not getting any errors in Aptana, so something I'm doing probably doesn't make sense. Basically, I am getting the value from a form and checking it against a regex. If the new checked variable isn't empty then I output to a different div that it is valid, and that it is not valid if the variable is empty.
<script type="text/javascript">
var age_regex=/(1[8-9]|2[0-9]|3[0-5])/;
var error_box= document.getElementById('error_box');
function checkAge(x){
var age = document.getElementById(x).value;
var checked_age = test.age_regex(age);
if (checked_age.value != "")
error_box.innerHTML = "Correct!";
else {
error_box.innerHTML = "Incorrect!";
}
}
</script>
Why regex for age ? How about this :
function checkAge(str) {
if(parseInt(str, 10) != str) {
return false;
}
if(parseInt(str, 10) < 18 || parseInt(str, 10) > 35)
{
return false;
}
}

Categories