How to make input required - javascript

What I want is that when both fields i.e. fname and lname are kept empty, the pop-up window should show both messages i.e. "First name must be filled out", "Last name must be filled out".
What modifications do I need to do?
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "") {
alert("First name must be filled out");
document.myForm.fname.focus();
return false;
}
var y = document.forms["myForm"]["lname"].value;
if (y == null || y == "") {
alert("Last name must be filled out");
document.myForm.lname.focus();
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">First name:
<input type="text" name="fname">Last name:
<input type="text" name="lname">
<input type="submit" value="Submit">
</form>
</body>

Perhaps this will give you some ideas about how to proceed:
function validateForm() {
var errors = [],
fname = document.forms["myForm"]["fname"],
lname = document.forms["myForm"]["lname"];
if (lname.value == "") {
errors.unshift("Last name must be filled out");
lname.focus();
}
if (fname.value == "") {
errors.unshift("First name must be filled out");
fname.focus();
}
if (errors.length > 0) {
alert("Cannot submit\n" + errors.join("\n"));
return false;
}
}
Demo: http://jsfiddle.net/MKdg5/
The first thing you'll notice is that it is easier to read because blocks are indented. Also:
You currently use document.forms["myForm"]["fname"] and document.myForm.fname to access the same field. Pick one way and use it consistently, or
Create a variable that references the field, fname, and then use fname.value and fname.focus()
Don't bother testing for null because the .value property never will be.
Instead of immediately alerting an error and returning, add the error text to an array and then at the end test if the array is empty.

You can go with Hthml 5 required. It's so much simpler and neat.
<form>
First name: <input type="text" name="fname" required="required">
Last name: <input type="text" name="lname" required="required">
<input type="submit" value="Submit">
</form>
Demo
Note: The required attribute is supported in Internet Explorer 10, Firefox, Opera, and Chrome. But it is not supported in Internet Explorer 9 and earlier versions, or in Safari.

Try to validate your field as:
if (!x || x.length == 0)

BAsed on your validateForm function, your code would never check the second field. When using the return statement, the function will stop executing, and return the specified value.
A solution is use nested if statements and check both fields in one conditional block
if (x==null || x=="")
{
if (y==null || y=="")
{
//codes for both are not validated
}
else
{
//codes for just x is not validated
}
}
else
if (y==null || y=="")
{
//codes for y is not validated
}
else
{
//codes for all validated
}
This way use of return statement in each block won't break your function execution

Related

How to make Javascript alert code all on one line

I'm trying to figure out how to make the alert code "First and Last Name must be filled out" if both of the fields of the form have no information inserted. I know how to do them individually, but how do you do make an alert code for both messages combined on one line? I am pretty new to Javascript..
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
var y = document.forms["myForm"]["lname"].value;
if (x == null || x == "") {
alert("First Name is missing information");
return false;
}
else (y == null || y == "") {
alert("Last Name is missing information")
return false;
}
else (x == null || x == "" && y == null || y == "") {
alert("First and Last name are missing information")
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp"
onsubmit="return validateForm()" method="post">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Delete all your JavaScript.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="demo_form.asp" method="post">
First Name: <input type="text" name="fname" required /><br />
Last Name: <input type="text" name="lname" required /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Notice the required attribute on the form.
Don't use JavaScript to do HTML's job.
Your logic needs to be reversed so that the case where both are null is checked first or the code will never get to it because either the x or y case happens first. Try:
var x = document.forms["myForm"]["fname"].value;
var y = document.forms["myForm"]["lname"].value;
var emptyX = x == null || x == "";
var emptyY = y == null || y == "";
if (emptyX && emptyY) {
alert("First and Last name are missing information")
return false;
}
else (emptyX) {
alert("First Name is missing information");
return false;
}
else (emptyY) {
alert("Last Name is missing information")
return false;
}
You should move your final else statement to the top. As your code currently exists, both fields will not be checked if either the first or last names are found to be empty.
Alternatively, you could add logic in each of x and y to check if the other is not empty but this isn't necessary if you just reverse the code.

form is submitting instead return false javascript

I am trying to test my form for validation. I don't have an .asp or .php file so I was informed I could use action="". My code doesn't seem to function right.On codepen it shows as values being posted. Jsfiddle gives me an error thats a paragraph long. In browser the page just seems to refresh. I have no alerts showing for anything....
what am I doing wrong here?
HTML:
<form name="name_form" action="" onsubmit="ValidateFormJS()" method="post">
First Name:
<input type="text" name="first_name">
<br> Last Name:
<input type="text" name="last_name">
<br>
<input type="submit" value="Submit">
</form>
Javascript:
function ValidateFormJS() {
var first = document.forms["name_form"]["first_name"].value;
var last = document.form["name_form"]["last_name"].value;
if (first == null || first == "") {
alert("First name must be filled out.");
return false;
} else if (last == null || last == "") {
alert("Last name must be filled out.");
return false;
} else {
alert("Form Submitted.");
return true;
}
}
The returned values from the function are never used.
You forgot return before the function call on onsubmit event.
onsubmit="return ValidateFormJS()"
Another problem is that you're using document.form to get the value of last name. It should be document.forms.
The last else can be removed.
Demo
var form = document.forms["name_form"];
function ValidateFormJS() {
var first = form["first_name"].value,
last = form["last_name"].value;
if (first == null || first == "") {
alert("First name must be filled out.");
return false;
} else if (last == null || last == "") {
alert("Last name must be filled out.");
return false;
}
}
<form name="name_form" action="" onsubmit="return ValidateFormJS()" method="post">
First Name:
<input type="text" name="first_name">
<br>Last Name:
<input type="text" name="last_name">
<br>
<input type="submit" value="Submit">
</form>
try this
in view
<form name="name_form" action="" onsubmit="return ValidateFormJS();" method="post">
in js code
function ValidateFormJS() {
var first = document.forms["name_form"]["first_name"].value;
var last = document.form["name_form"]["last_name"].value;
if (first == null || first == "") {
alert("First name must be filled out.");
return false;
} else if (last == null || last == "") {
alert("Last name must be filled out.");
return false;
}
alert("Form Submitted.");
return true;
}

JavaScript no response with validation

I am new to javascript and I am attempting to create a simple form validation. When I hit the submit button nothing happens. I have been looking at examples for a while and I cannot seem to figure out where I am going wrong. Any suggestions:
Right after this post I am going to break it all down and start smaller. But in the meantime I figured another set of eyes couldn't hurt and it is very possible I am doing something horribly wrong.
HTML:
<form name="form" action="index.html" onsubmit="return construct();" method="post">
<label>Your Name:<span class="req">*</span> </label>
<input type="text" name="name" /><br />
<label>Company Name:<span class="req">*</span> </label>
<input type="text" name="companyName" /><br />
<label>Phone Number:</label>
<input type="text" name="phone" /><br />
<label>Email Address:<span class="req">*</span></label>
<input type="text" name="email" /><br />
<label>Best Time to be Contacted:</label>
<input type="text" name="TimeForContact" /><br />
<label>Availability for Presenting:</label>
<input type="text" name="aval" /><br />
<label>Message:</label>
<textarea name="message" ROWS="3" COLS="30"></textarea>
<label>First Time Presenting for AGC?:<span class="req">*</span></label>
<input type="radio" name="firstTime" value="Yes" id="yes" /><span class="small">Yes</span>
<input type="radio" name="firstTime" value="No" id="no"/><span class="small">No</span><br /><br />
<input type="submit" name="submit" value="Sign-Up" />
</form>
JavaScript:
function construct() {
var name = document.forms["form"]["name"].value;
var companyName = document.forms["form"]["companyName"].value;
var email = document.forms["forms"]["email"].value;
var phone = document.forms["forms"]["phone"].value;
var TimeForC = document.forms["forms"]["TimeForContact"].value;
var availability = document.forms["forms"]["aval"].value;
if (validateExistence(name) == false || validateExistence(companyName) == false)
return false;
if (radioCheck == false)
return false;
if (phoneValidate(phone) == false)
return false;
if (checkValidForOthers(TimeForC) == false || checkValidForOthers(availability) == false)
return false;
if (emailCheck(email) == false)
return false;
}
function validateExistence(name) {
if (name == null || name == ' ')
alert("You must enter a " + name + " to submit! Thank you."); return false;
if (name.length > 40)
alert(name + " is too long for our form, please abbreviate."); return false;
}
function phoneValidate(phone) {
if (phone.length > 12 || phone == "" || !isNaN(phone))
alert("Please enter a valid phone number."); return false;
}
function checkValidForOthers(name) {
if (name.length > 40)
alert(name + " is too long for our form, please abbreviate."); return false;
}
function messageCheck(message) {
var currentLength = name.length;
var over = 0;
over = currentLength - 200;
if (name.length > 200)
alert(name + " is too long for our form, please abbreviate. You are " + over + " characters over allowed amount"); return false;
}
function radioCheck() {
if (document.getElementById("yes").checked == false || document.getElementById("no").checked == false)
return false;
}
function emailCheck(email) {
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;
}
}
Am I calling my functions incorrectly? I honestly am not sure where I am going wrong.
I don't understand how to debug my code... I am using chrome and I am not receiving any errors in the console. Is there a way to set breakpoints to step through the javascript?
I realize i just threw a lot of code up there so thanks in advance for sifting through it.
Here is mistake:
Replace var email = document.forms["forms"]["email"].value;
by var email = document.forms["form"]["email"].value;
There are lot of places in your js :
var email = document.forms["forms"]["email"].value;
var phone = document.forms["forms"]["phone"].value;
var TimeForC = document.forms["forms"]["TimeForContact"].value;
var availability = document.forms["forms"]["aval"].value;
where you mistyped form as forms.
Is there a way to set breakpoints to step through the javascript?
Yes there is a way to set breakpoints:
Refer following links in order to know the method to set break-point in debugger console in Chrome:
LINK 1
LINK 2
The following should fix the immediate problem:
function construct(form) {
var
name = form["name"].value,
companyName = form["companyName"].value,
email = form["email"].value,
phone = form["phone"].value,
TimeForC = form["TimeForContact"].value,
availability = form["aval"].value
;
if (!validateExistence(name) || !validateExistence(companyName)) {
return false;
}
else if (!radioCheck) {
return false;
}
else if (phoneValidate(phone) == false) {
return false;
}
else if (!checkValidForOthers(TimeForC) || !checkValidForOthers(availability)) {
return false;
}
else if (emailCheck(email) == false) {
return false;
}
}
You had a typo in the form document.forms["forms"], where 'forms' doesn't exist. Instead of always traversing objects to get to your form, you can use this to pass the current element into your function.
<form action="index.html" onsubmit="return construct(this);" method="post">
If you're starting out it's also a good idea to make sure you set all your braces (i.e. curly brackets) as this will help you avoid getting confused with regards to alignment and brace matching.
Your first problem is the forms where you meant form. See here
But you have other problems with your validation code, for example:
if (name == null || name == ' ')
Here you are checking if name is null or name is a single space. I assume you wanted to check if the field is blank, but a completely empty string will evaluate as false in your condition, as will two spaces. What you probably want to do is something like this:
if (!name) {
// tell the user they need to enter a value
}
Conveniently (or sometimes not), Javascript interprets null, an empty string, or a string full of white space as false, so this should cover you.
You also have a whole host of other problems, see this:
http://jsfiddle.net/FCwYW/2/
Most of the problems have been pointed out by others.
You need to use braces {} when you have more than one line after an
if statement.
You need to return true when you pass you validation
tests or Javascript will interpret the lack of a return value as false.
Your radioCheck will only pass if both radio buttons are checked.
You where checking that your phone number was NOT NaN (i.e. it is a number) and returning false if it was.
I would suggest learning some new debug skills. There are ways to break down a problem like this that will quickly isolate your problem:
Commenting out code and enabling parts bit by bit
Using a debugger such as Firebug
Using console.log() or alert() calls
Reviewing your code line-by-line and thinking about what it is supposed to do
In your case, I would have first seen if name got a value with a console.log(name) statement, and then moved forward from there. You would immediately see that name does not get a value. This will lead to the discovery that you have a typo ("forms" instead of "form").
Some other errors in your code:
You are returning false outside of your if statement in validateExistence():
if (name == null || name == ' ')
alert("You must enter a " + name + " to submit! Thank you.");
return false;
In this case, you do not have brackets {} around your statement. It looks like return false is in the if(){}, but it is not. Every call to this code will return false. Not using brackets works with a single call, but I don't recommend it, because it leads to issues like this when you add additional code.
In the same code, you are using name as the field name when it is really the value of the field:
alert("You must enter a " + name + " to submit! Thank you."); return false;
You really want to pass the field name separately:
function validateExistence(name, field) {
if (name == null || name == ' ') {
alert("You must enter a " + field + " to submit! Thank you.");
return false;
} else if (name.length > 40)
alert(field + "value is too long for our form, please abbreviate.");
return false;
}
}
You are not calling radioCheck() because you are missing parentheses:
if (radioCheck == false)
In radioCheck(), you are using || instead of &&. Because at least 1 will always be unchecked by definition, you will always fail this check:
if (document.getElementById("yes").checked == false || document.getElementById("no").checked == false) return false;
And more...
My suggestion is to enable one check at a time, test it, and once it works as expected, move on to the next. Trying to debug all at once is very difficult.
replace var email = document.forms["forms"]["email"].value;
by
var email = document.forms["form"]["email"].value;
Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var data; //The Values can be like as null,blank,undefined,zero you can test
if(!(!(data)))
{
alert("data "+data);
}
else
{
alert("data is "+data);
}
}

stop form during submission if it validates incorrectly

I am trying to use JavaScript to validate forms but if the form doesn't validate, I don't want the form to be sent to the "action" page.
The validator:
<script>
function formSubmit()
{
document.getElementById("signup_form").submit();
var x=document.forms["signup_form"]["tname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
The form itself:
<form action="some_file.php" method="post" id="signup_form" name="signup_form" onsubmit="return formSubmit()">
But all this does is if the tname field empty, it will return an alert but as soon as the user hits ok, the form then redirects to some_file.php. What have I missed here?
The submit button:
Signup
So what have I missed? How do I avoid this in the future?
You have the wrong execution of statememts. You are submitting the form before validating. Move this statement below the if statement
document.getElementById("signup_form").submit();
further to this. you are calling formSubmit() at two places, form tag and a tag doing it once is fine.
UPDATED CODE:
<html>
<head>
<title></title>
<script>
function formSubmit()
{
var x=document.forms["signup_form"]["tname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
document.getElementById("signup_form").submit();
}
</script>
</head>
<body>
<form action="some_file.php" method="post" id="signup_form" name="signup_form" onsubmit="return formSubmit()">
<input type="text" name="tname" />
Signup
</body>
</html>
DEMO
Try this:
function formSubmit()
{
var x=document.forms["signup_form"]["tname"].value;
if (x=="")
{
alert("First name must be filled out");
return false;
}
return true;
}
*Changes made to your code: *
- There is no need for formSubmit to try to submit the form! Just perform the validation checks and return true if you want the submission to proceed or false otherwise.
Also you do not need to check for the x == null case. If the textbox is empty, its value will be "".
What might be needed though is a check that x does not just contain spaces. If you do not care about supporting older browsers you can use the new Javascript trim function. If you care about backwards compatibility, either try one of the many javascript libraries that offer trim or the following:
function formSubmit()
{
var x=document.forms["signup_form"]["tname"].value.replace(/^\s+|\s+$/g, '');
if (x=="")
{
alert("First name must be filled out");
return false;
}
return true;
}
If I just wanted to avoid submitting spaces I would have left the var x= bit as it was and added the replace in the check making it if(x.replace(/\s/g, '') == ""). However, I also want to trim the input so that if the user enters " user1" or "user1 " the form will send "user1".
You can see the three different versions versions working here:
http://jsfiddle.net/9LPfb/2/
http://jsfiddle.net/9LPfb/3/
http://jsfiddle.net/9LPfb/6/
you have problem with your program flow .
do validation before the submitting form.
there is no use of validating after submitting, i think you have mistakenly made it.
just submit after validation.
try:
function formSubmit() {
var x=document.forms["signup_form"]["tname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
else {
return true;
}
}
You already had all the code. It was becos of wrong execution.
<script>
function formSubmit()
{
var x=document.forms["signup_form"]["tname"].value;
if (!x){
alert("First name must be filled out");
return false;
}
return true;
}
</script>
<form action="some_file.php" method="post" id="signup_form" name="signup_form">
Signup
in your function just remove this line
document.getElementById("signup_form").submit();
and add it after the if condition
or rewrite the function like the one below
function formSubmit()
{
var x=document.forms["signup_form"]["tname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}else
return true;
}
Contact Form
function empty() {
var x,y;
x = document.forms["ff"]"name"].value;
y = document.forms["ff"]["surname"].value;
if(x=="" ||x==null){
alert("Enter your name");
return false;
}else if(y==""){
alert("Enter your surname");
return false;
}else{
alert('Data is sending');
return true;
}
};
In the html:
<form method="POST" action="formdata.php" name="ff"onsubmit="return empty()">
<table>
<tr>
<td>Enter Your Name : <input type="text" name="name" maxlength="30" size="40" id="na" ></td>
</tr>
<tr>
<td>Enter Your Surname : <input type="text" name="surname" maxlength="30" size="40" id="sna"></td>
</tr>
<tr>
<td>
<input type="submit" name="formsubmit" value="submit" >
</td>
</tr>
</table>
</form>

JavaScript data validation

Please help me. The validation is not working:
<script type="text/javascript" src="javascript.js">
function validation()
{
var fname=document.forms["form1"]["fname"].value;
var lname=document.forms["form1"]["lname"].value;
var idnumber=document.forms["form1"]["idnumber"].value;
var email=document.forms["form1"]["email"].value;
var atpos=email.indexOf("#");
var dotpos=email.lastIndexOf(".");
var address=document.forms["form1"]["address"].value;
var phonenumber=document.forms["form1"]["phonenumber"].value;
if (fname==null || fname=="")
{
alert("Name should be entered correctly");
return false;
}
if (lname==null || lname=="")
{
alert("Name should be entered correctly");
return false;
}
if (isNaN(idnumber))
{
alert("Please enter a valid id number");
return false;
}
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Please enter a valid e-mail address");
return false;
}
if(address==null || address=="")
{
alert("Please insert your address");
return false;
}
if (isNaN(phonenumber))
{
alert("Please enter a valid phone number");
return false;
}
}
</script>
<form name="form1" action="validation.php" method="post" onsubmit=" return validation(this);return false">
Firstname:<input type="text" name="fname"><br/>
Lastname:<input type="text" name="lname"><br/>
Nation ID Number:<input type="text" name="idnumber" minlength="8"maxlength="8"><br/>
Email address: <input type="text" name="email"><br/>
Address:<input type="text" name="address"><br/>
Pnone number:<input type="text" name="phonenumber"><br/>
<input type="reset" name="reset" value="reset">
<input type="submit" name="submit" value="submit">
</form>
There are a number of issues with that code:
You really should not use the same <script> element for both calling src="javascript.js" and at the same time declare a function. Use separate elements, like this:
<script type="text/javascript" src="javascript.js"></script>
<script type="text/javascript">
function validation()
{
...
}
</script>
In the <form> element, there's a redundant ;return false. The form will take the value from return validation(this), anything after it will be ignored. Also, no need of ";" when using in-line javascript.
You are passing passing this as argument to the validation() function, but validation is expecting no argument. Should be:
function validation(oForm)
If you are already passing this, why not use it? this is a reference to the element itself, so it is, for the validation function, a reference to the form. So no need to name the form.
<form action="validation.php" method="post" onsubmit="return validation(this)">
And the references in function would be:
function validation(oForm)
{
var fname=oForm["fname"].value;
var lname=oForm["lname"].value;
}
Those changes alone could solve your problem. I'll check the code further to see if there is something else.
EDIT:
I've tested the validation now, and it works. The only required modification is removing the scr=validation.js from your <SCRIPT> tag. Use separate tags for that, as i suggested.
But i strongly suggest you consider the other issues I've mentioned.
Also, other suggestions regarding the validation itself:
For alphanumerical fields, no need to check for null, only "" is enough. You can simply use:
if (lname=="")
First Name and Last Name error messages are the same. That will confuse users.
Avoid testing phone numbers as numeric. Remember "(407) 234-5678" is a perfectly valid phone number, although it will fail your test. Unless you have a strong reason to treat it as numeric (automatic dialing?), leave it as an ordinary, text field.
In the National ID field: There is no minlength in HTML. Only maxlength
isNaN(idnumber) will return true if value is blank. And also if length<8. I assume it is a required field with a required length, so you should use:
if (isNaN(idnumber) || idnumber.length != 8)
{
alert("Please enter a valid id number");
return false;
}
For all your tests, consider trimming the values. Currently, input like " " (blanks only) WILL pass your test. Javascript has no built-in trim function, but it can be done with this:
function trim( texto ) {
return texto.replace(/^\s*|\s*$/g, "");
}
And used like this:
var fname=trim(oForm["fname"].value);
For clarity, use an explicit return true; in validation() after all tests successful.
Here is the suggested code after all changes:
<script type="text/javascript" scr="validation.js"></script>
<script type="text/javascript">
function validation(oForm)
{
var fname = trim(oForm["fname"].value);
var lname = trim(oForm["lname"].value);
var idnumber = trim(oForm["idnumber"].value);
var email = trim(oForm["email"].value);
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
var address = trim(oForm["address"].value);
var phonenumber = trim(oForm["phonenumber"].value);
if (fname=="")
{
alert("First name should be entered");
return false;
}
if (lname=="")
{
alert("Last name should be entered");
return false;
}
if (isNaN(idnumber) || idnumber.length != 8)
{
alert("Please enter a valid id number");
return false;
}
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Please enter a valid e-mail address");
return false;
}
if(address=="")
{
alert("Please insert your address");
return false;
}
if (isNaN(phonenumber))
{
alert("Please enter a valid phone number");
return false;
}
return true;
}
function trim( texto ) {
return texto.replace(/^\s*|\s*$/g, "");
}
</script>
<form name="form1" action="validation.php" method="post" onsubmit="return validation(this)">
Firstname:<input type="text" name="fname"><br/>
Lastname:<input type="text" name="lname"><br/>
Nation ID Number:<input type="text" name="idnumber" maxlength="8"><br/>
Email address: <input type="text" name="email"><br/>
Address:<input type="text" name="address"><br/>
Pnone number:<input type="text" name="phonenumber"><br/>
<input type="reset" name="reset" value="reset">
<input type="submit" name="submit" value="submit">
</form>

Categories

Resources