Javascript validate form OR function - javascript

I am trying to ask the user to input at least 1 of the options. From my codes the user need to input all the inputs. Can anyone please check what is wrong with my code?
jsp
<form role="form" method="POST" id="search" action="Servlet"
onsubmit="return validateForm();">
<label>Name</label>
<input name="name">
<label>ID</label>
<input name="id">
<label>no</label>
<input name="no">
<button type="submit">Search</button>
</form>
javascript
function validateForm() {
var name = document.forms["search"]["name"].value;
var id = document.forms["search"]["id"].value;
var no = document.forms["search"]["no"].value;
if ( (name == null || name == "") || (id == null || id == "") || (no == null && no == "")) {
alert("Please enter either one to perform search");
return false;
}
}

Just a little logic adjustment should do the trick:
if (
(name != null || name != "") ||
(id != null || id != "") ||
(no != null && no != "")
) {
This is saying that if any one of the fields has a value, continue.

function validateForm() {
var name = document.forms["search"]["name"].value;
var id = document.forms["search"]["id"].value;
var no = document.forms["search"]["no"].value;
if ( (name == null || name == "") && (id == null || id == "") && (no == null || no == "")) {
alert("Please enter either one to perform search");
return false;
}
}
or you would do it as #isherwood did. also take care of typos like not closing your input tag
should goes like this <input name="no"/> good luck and I hope this would help

Related

Check to see if form fields are empty using javascript

I currently have a working function that checks if all of the forms fields are not blank. For part of a form, i have a hidden div that will appear if one of the fields has an answer of yes selected in the drop down. when i have the drop down item selected as yes, i would like for the function to check if any one of those fields are left empty, and when the drop down has an answer of no, i don't want the function to check the values of the hidden div items. i can't seem to figure out a way to accomplish this. this is what i have tried so far. the variable label2 contains the value of the drop down menu, Yes/No.
function validateOverage()
{
var drive2 = document.forms["overage"]["drivers2"].value;
var prodes2 = document.forms["overage"]["proddes2"].value;
var sizes2 = document.forms["overage"]["size2"].value;
var cases2 = document.forms["overage"]["cs2"].value;
var bottle2 = document.forms["overage"]["btls2"].value;
var initials2 = document.forms["overage"]["chkitls2"].value;
var label2 = document.forms["overage"]["ontrucks"].value;
var routenum2 = document.forms["overage"]["routenum"].value;
var stopnum2 = document.forms["overage"]["stopnum"].value;
var custnum2 = document.forms["overage"]["custnum"].value;
if (drive2 == null || drive2 == "" || prodes2 == null || prodes2 == "" || sizes2 == null || sizes2 == "" || cases2 == null || cases2 == ""||
bottle2 == null || bottle2 == "" || initials2 == null || initials2 == "" || label2 == null || label2 == "")
{
alert("Fill in all Fields for the Overage form");
return false;
}
else if (label2 == "Yes" || routenum2 == null || routenum2 == "" || stopnum2 == null || stopnum2 == "" || custnum2 == null || custnum2 == "")
{
alert("Fille in all Fields for the Overage form");
return false;
}*/
else if (cases2 == "0" && bottle2 == "0")
{
alert("Both cases and bottles values can not be 0");
return false;
}
else
{
alert("Data Added to the Overage form");
}
}
html code that i have in my body that has the hidden contents
<td style = "visibility: hidden"><input type = "number" id = "routenum"> </input></td>
<td style = "visibility: hidden"><input type = "number" id = "stopnum"> </input></td>
<td style = "visibility: hidden"><input type = "number" id = "custnum"> </input></td>

Need a If and else statement and a new page

This is what i need help with!
My project needs a If and else statement for the Age part!
and then send the person who has validated correctly to a new page.. I currently have a page but that is just something that is in my USB
also need to explain how its is validating
Please help
!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "")
{
alert("Name must be filled out");
return false;
}
var Age = document.forms["myForm"]["Age"].value;
if (Age == null || Age == "") {
alert("Has to be a number between 1 and 150");
return false;
}
var Email = document.forms["myForm"]["Email"].value;
if (Email == null || Email == "") {
alert("Make sure it is the correct Email format");
return false;
}
var myCheck = document.getElementById("check1").checked;
if (myCheck == false) {
alert("Have to tick box to proceed");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="file:///G:/Welcome.html"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
Age: <input type="text" name="Age">
Email: <input type="text" name="Email">
<br>checkbox: <input type="checkbox" id="check1" name="myCheck"> </br>
<input type="submit" value="click">
</form>
</body>
</html>
You could extend the if clause with the age check.
var age = document.forms["myForm"]["Age"].value;
if (age == "" || age < 1 || age > 150) {
// ^^^^^^^^^^^^^^^^^^^^^^^
alert("Has to be a number between 1 and 150");
return false;
}
I'd parse the value of the form into a number and then I'd check its range:
var age = Number(document.forms["myForm"]["Age"].value) || 0;
if (age < 1 || age > 150) {
alert("Has to be a number between 1 and 150");
return false;
}
Why convert to number and put Number(document.forms["myForm"]["Age"].value) || 0?
The reason is simple: imagine that a malicious user put in your form the value "NaN". If you didn't do this check, the value of age would be NaN and it'd pass your check (NaN < 1 is false and NaN > 150 is false too).
This way, if a user put "NaN" in the form, the guard would transform it into 0, the alert would trigger and the function would return false.

Validate and display window alert

how do I validate to ensure a value for total or orderForm have been fill up if not it will display a window alert upon clicking on Submit button ?
It seems the below is not working at all .
Pure JS:
function va(){
var result = false;
var w = document.forms["orderForm"]["companyName"].value;
var x = document.forms["orderForm"]["forename"].value;
var y = document.forms["orderForm"]["surname"].value;
var z = document.forms["orderForm"]["total"].value;
if (x == null || x == "") && (y == null || y == "") && (w == null || w == ""){
window.alert('Name must be Filled out');
result = false;
// } else if (z = < 5){
// window.alert('Please Select A CD');
// return false;
// }else {
// return true;
}
return result;
}
HTML:
<section id="checkCost">
<h3>Total cost</h3>
Total <input type="text" name="total" id="total" size="10" readonly="readonly" />
</section>
<section id="placeOrder">
<h3>Place order</h3>
Your details
Customer Type: <select id="show" name="customerType" onchange="change(this)">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
<div id="retCustDetails" class="custDetails" style="display:none">
Forename <input type="text" name="forename" id="forename" />
Surname <input type="text" name="surname" id="surname" />
</div>
<p><input type="submit" name="submit" value="Order now!" id="sub1" disabled="disabled"/></p>
try this:
if (x == null || x == "") {
window.alert('forename must be Filled out');
result = false;
} else if (y == null || y == "") {
window.alert('surname must be Filled out');
result = false;
} else if (w == null || w == "") {
window.alert('companyName must be Filled out');
result = false;
}
return result;
Try:
if ((x == null || x == "") || (y == null || y == "") || (w == null || w == ""))
EDIT:
Sure thing, original line:
if (x == null || x == "") && (y == null || y == "") && (w == null || w == "")
I did two things. Switch out the && for || and wrap the if condition in an inclusive set of parenthesis (which probably isn't required but I do it for neatness). The original if statement reads as "if condition and condition and condition" meaning all conditions have to return true (i.e. be blank) in order to continue. I believe each of these values are required to validate the form. My proposed if statement would read "if condition or condition or condition" letting the alert box be displayed if any value is empty.

How to include an external Javascript to html5

Problem: External javascript is not working.
I want my registration page to be validated and I have written the code but I don't know where to call it I tried the following.
This is my javascript code:
var emailRegex = /^[A-Za-z0-9._]*\#[A-Za-z]*\.[A-Za-z]{2,5}$/;
var fname = document.form.Name.Value;
var lname = document.form.Last.value;
var fpassword = document.form.password.value;
var frassword = document.form.repassword.value;
var femail = document.form.Email.value;
function submit()
{
if ( fname === "")
{
document.form.Name.focus();
alert("Please enter the name");
return false;
}
if ( lname === "")
{
document.form.Last.focus();
alert("Please enter last name");
return false;
}
if( fpassword === "")
{
document.form.password.focus();
alert("You can't leave password empty");
return false;
}
if( frassword === "")
{
document.form.repassword.focus();
alert("Please confirm password");
return false;
}
if( femail === "")
{
document.form.Email.focus();
alert("Don't leave Email blank");
return false;
}
else if (!emailRegex.test(femail))
{
document.form.Email.focus();
alert("Not a valid Email");
return false;
}
if( fname !== '' && lname !== '' && fpassword !== '' && frassword !== '' && femail !== '')
{
alert("Registration sucessfull");
}
}
I tried like this :
<script type="text/javascript" src="skill.js"></script>
<script>
submit();
</script>
And I tried this too:
<form name="form" onclick="submit()">
create a submit button inside the form element like this -
<input type="submit" value="Submit" />
and then add an attribute on the opening form tag, like this-
<form name="form" onsubmit="submit()">
make sure you have linked to you JS file already.

onclick event of input button type is not working in chrome for some users

Here is my html code
<input type="button" name="Button" value=" Next " runat="server" id="btnNext" class="button" onclick ="if (!EmptyCheck()) return false;" />
and
function EmptyCheck() {
debugger;
var txtRSI = $("input[id$=txtRSI]").val();
var txtQFix = $("input[id$=txtQFix]").val();
var txtPassPercent = $("input[id$=txtPassPercent]").val();
var txtDefRejRate = $("input[id$=txtDefRejRate]").val();
var txtBuildVar = $("input[id$=txtBuildVar]").val();
var txtEffortVar = $("input[id$=txtEffortVar]").val();
var txtScheVar = $("input[id$=txtScheVar]").val();
var txtDeliMet = $("input[id$=txtDeliMet]").val();
var txtBudgetVar = $("input[id$=txtBudgetVar]").val();
var ddlOwner = $('select[id$="ddlOwner"]').val();
var ddlAccount = $('select[id$="ddlAccount"]').val();
var ddlProgramme = $('select[id$="ddlProgramme"]').val();
var ddlMonth = $('select[id$="ddlMonth"]').val();
var ddlYear = $('select[id$="ddlYear"]').val();
if ((txtRSI == "") || (txtQFix == "") || (txtPassPercent == "") || (txtDefRejRate == "") || (txtBuildVar == "") || (txtEffortVar == "") || (txtScheVar == "") ||
(txtDeliMet == "") || (txtBudgetVar == "") || (ddlOwner == "-1") || (ddlAccount == null) || (ddlProgramme == null) || (ddlMonth == 0) || (ddlAccount == "-1")
|| (ddlProgramme == "-1") || (ddlYear == 0)) {
alert("All fields are Mandatory");
return false;
}
else {
return true;
}
}
This is javascript method works fine in my browser.whereas the same is not working for others.
couldnt find why this happens..
inline code is not supported in chrome..i saw this in several posts..but it works for me..but not for others.. can somebody give an alternate solution to this???
also i have server side implememnted...wanted to achieve both.
i have tried like this also
getelementbyid('btnid').addeventlistener('click', function()){}
Have you tried just using the function? If your function returns a boolean value, why are you checking it to then return another boolean value? Just return EmptyCheck()
However, I will say that using the inline functions in my experience has been a poor decision. The functions can be managed/called more efficiently from an external jscript file. Here's an example:
Step 1
In your .js file, create a generic (but not anonymous) function for each page. For examples, we'll work in a hypothetical "Home" page.
function HomePageEvents() {
}
Step 2
Now we have a function that will serve as a container for your home page's javascript . . . But of course we need to run the function at some point. Well, we want to make sure the function is run once the document is finished loading of course, since we'll likely need to reference elements of the rendered page. So let's go ahead and create an anonymous function that will trigger this container function (aka, HomePageEvents() function). In your Home page, add the following:
<script type="text/javascript">
$(document).ready({function(){
HomePageEvents();
});
</script>
Step 3
What was it we were trying to do again? Oh, right! We want to add a click event for your button. Well, we can first start by creating the function for the click event. Now, I'm assuming your button has some kind of innate functionality, and all we are doing here is validating the button. If this is indeed the case, all we need to do is return a true or false indicating whether the event should continue.
function HomePageEvents() {
// Function to perform our validation.
function validateNext() {
if ((txtRSI == "") || (txtQFix == "") || (txtPassPercent == "") || (txtDefRejRate == "") || (txtBuildVar == "") || (txtEffortVar == "") || (txtScheVar == "") || (txtDeliMet == "") || (txtBudgetVar == "") || (ddlOwner == "-1") || (ddlAccount == null) || (ddlProgramme == null) || (ddlMonth == 0) || (ddlAccount == "-1") || (ddlProgramme == "-1") || (ddlYear == 0)) {
alert("All fields are Mandatory");
return false;
} else {
return true;
}
};
};
Step 4
Now that we have the validation function ready, we just need to add the function as a click event for our btnNext button.
function HomePageEvents() {
// Add function to btnNext button . . .
$('#btnNext').on('click', function(){
validateNext();
});
// Function to perform our validation.
function validateNext() {
if ((txtRSI == "") || (txtQFix == "") || (txtPassPercent == "") || (txtDefRejRate == "") || (txtBuildVar == "") || (txtEffortVar == "") || (txtScheVar == "") || (txtDeliMet == "") || (txtBudgetVar == "") || (ddlOwner == "-1") || (ddlAccount == null) || (ddlProgramme == null) || (ddlMonth == 0) || (ddlAccount == "-1") || (ddlProgramme == "-1") || (ddlYear == 0)) {
alert("All fields are Mandatory");
return false;
} else {
return true;
}
};
};
The end result is you get (1) all your javascript in a single file--which is better for caching, (2) the file is easily manageable, and (3) you can isolate code for each page.
As an alternate you can use jQuery click event. Read documentation from here .
$('.button').click(function(){ // button is the class name of your input control
// Your EmptyCheck Logic goes here.
});
Note that there are other solutions as well to bind click event using jQuery like .on().
$('.button').on('click', function() {
// Your EmptyCheck Logic goes here.
});
Hope this helps!

Categories