I am new to JavaScript and I have been doing a university assignment based around HTML and JavaScript. In this assignment I was asked to create a number of forms to allows a person to register for some form of educational classes. I was asked to create the form using HTML and to validate the entries using only JavaScript.
What I have been struggling to figure out is how to validate more than one form input using one block of validation (if that is possible), I want to validate both the firstname and familyname inputs using only validateForm.
Here is a segment I have been testing out:
<head>
<script>
function validateForm() {
var x = document.forms["nameform"]["firstname"].value;
if (x == null || x == "") {
alert("first name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="nameform" , action="demo_form.asp" , onsubmit="return validateForm()" , method="post">
<b>First name:</b>
<input type="text" name="firstname">
<br>
<b>Family name:</b>
<input type="text" name="familyname">
<br>
<input type="submit" value="Submit">
</form>
</body>
Any help would be greatly appreciated!
<head>
<script>
function validateForm()
{
var firstname=document.getElementById('txtfirstname');
var familyname=document.getElementById('txtfamilyname');
if (firstname.value=="")
{
alert("first name must be filled out");
return false;
}
if (familyname.value=="")
{
alert("familyname must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="nameform", action="demo_form.asp", onsubmit="return validateForm()", method="post">
<b>First name:</b> <input type="text" id="txtfirstname" name="firstname">
<br>
<b>Family name:</b> <input type="text" id="txtfamilyname" name="familyname">
<br>
<input type="submit" value="Submit">
</form>
</body>
You can check all inputs, store error messages (if any) and return false at the end if there is even one failure.
i.e.
function validateForm() {
var x = document.forms["nameform"]["firstname"].value, errors = [];
if (x == null || x == "") {
errors.push("first name must be filled out");
}
x = document.forms["nameform"]["familyname"].value;
if (x == null || x == "") {
errors.push("family name must be filled out");
}
if(errors.length > 0) { // check if there were any errors
alert(errors.join("\n")); // alert all messages together
return false;
}
}
Couple of possibilities...
<script>
function validateForm()
{
var x=document.forms["nameform"]["firstname"].value;
if (x==null || x=="")
{
alert("first name must be filled out");
return false;
}
x=document.forms["nameform"]["lasttname"].value;
if (x==null || x=="")
{
alert("last name must be filled out");
return false;
}
return true;
}
</script>
will present an alert for each field as it fails validation and return true if all fields are OK.
<script>
function validateForm()
{
var errorString="";
var x=document.forms["nameform"]["firstname"].value;
if (x==null || x=="")
{
errorString+="first name must be filled out\n";
}
x=document.forms["nameform"]["lasttname"].value;
if (x==null || x=="")
{
errorString+="last name must be filled out\n";
}
if(errorString=="")
{
return true;
}
else
{
alert(errorString);
return false;
}
}
</script>
will return a single alert listing all of the fields that have failed validation.
In addition, I always like to use the focus() method on the first field that failed validation to put the cursor in the field that needs correcting.
Try this..
function validateForm()
{
var msg='';
var flag=false;
var x = document.forms["nameform"]["firstname"].value;
if (x == null || x == "")
{
flag = true;
msg = ' First Name '
}
x = document.forms["nameform"]["familyname"].value;
if (x == null || x == "")
{
if(flag==true)
msg = msg + 'And Family Name '
else
msg = msg + ' Family Name ';
flag = true;
}
if (flag==true) {
msg = msg + " must be filled out";
alert(msg);
}
return false;
}
simply store it in multiple variables and have multiple if statements:
<script>
function validateForm() {
// name the variables appropriately
var firstname = document.forms["nameform"]["firstname"].value;
var familyname = document.forms["nameform"]["familyname"].value;
// check if either of them are correct, if not alert and return false.
if (firstname == null || firstname == "") {
alert("first name must be filled out");
return false;
} else if (familyname == null || familyname == ""){
alert("family name must be filled out");
return false;
}
return true;
}
</script>
Related
I just made a registration form which will tell you in red(CSS) letters if something is wrong. However I want this text to go away as soon as the user writes it correctly. How do I do that?
<script>
function validateForm2() {
var usrnm2 = document.getElementById("usrnm2").value;
var passw2 = document.getElementById("passw2").value;
var cnfpassw2 = document.getElementById("cnfpassw2").value;
var age = document.getElementById("age").value;
if (usrnm2 == null || usrnm2 == "") {
document.getElementById("error1").innerHTML = "You must enter a username";
return false;
}
else if (passw2 == null || passw2 == "") {
document.getElementById("error2").innerHTML = "You must enter a password";
return false;
}
else if (cnfpassw2 !== passw2) {
document.getElementById("error3").innerHTML = "Password does not match";
return false;
}
else if (age < 18) {
document.getElementById("error4").innerHTML = "You are not old enough to enter this site"
return false;
}
else {
alert("Congratulations, you have registered successfully!")
}
}
</script>
<script>
function register2() {
validateForm2()
}
</script>
<form>
Username:
<input id="usrnm2" type="text" name="username"><p id="error1"></p>
Password
<input id="passw2" type="password" name="password"><p id="error2"></p>
Confirm Password
<input id="cnfpassw2" type="password" name="confirmpw2"><p id="error3"></p>
Age
<input id="age" type="number" name="age"><p id="error4"></p><br />
<input id="bttn2" type="button" value="Register!" onclick="register2()"><br />
</form>
Separate the validation conditions into single block if statements, and then include a handler for returning the fields to normal when they are entered correctly:
if (field is entered incorrectly) {
document.getElementById("error").innerHTML = "You must enter correctly";
return false;
}
else {
document.getElementById("error").innerHTML = "";
}
...
alert("Congratulations, you have registered successfully!");
You simply need to place the alert after all of the statements - it will execute as long as none of the conditions fail and thus return.
can someone please tell me what is going wrong?
I am trying to create a basic login page and that opens only when a correct password is written
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
var x=document.forms["myForm"]["fname2"].value;
if (x==null || x=="")
{
alert("password must be filled out");
return false;
}
}
function isValid(myNorm){
var password = myNorm.value;
if (password == "hello_me")
{
return true;
}
else
{alert('Wrong Password')
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="helloworld.html" onsubmit="return !!(validateForm()& isValid())" method="post">
Login ID: <input type="text" name="fname"> <br />
<br>
Password: <input type="password" name="fname2" > <br />
<br />
<br />
<input type="submit" value="Submit">
<input type="Reset" value="clear">
</form>
</body>
</html>
Password value is undefined in 2nd function because you are not using any params when calling isValid() function
var password = myNorm.value; //`myNorm` is undefined
to
var password = document.forms["myForm"]["fname2"].value;
See below correct function
function isValid(myNorm){
var password = document.forms["myForm"]["fname2"].value;
if (password == "hello_me"){
return true;
} else {
alert('Wrong Password')
return false;
}
}
Updated Answer on comment
if value is valid in function validateForm() then return true, see below
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
var x=document.forms["myForm"]["fname2"].value;
if (x==null || x=="")
{
alert("password must be filled out");
return false;
}
return true; // return true when input value is value
}
FIDDLE DEMO
alert for wrong password in isvalid() needs a semicolon.
The And operator is && not & in the on submit call
I am just eye balling the code
What did you observe?
You cld use ie to debug using F12 key.. Or Firefox with the suitable plugin
I am currently working on an Email form and have little experience with javascript but am close to accomplishing what I need but struggling at one point, spent hours trying everything I can find searching and figured someone on here would probably have my answer instantly.
I currently have 3 functions checking a box is filled, email is correct format and passwords match.
If I set each function to run on its own upon clicking submit they work perfectly for their own intended purpose, however I am having trouble working out how to make it so that all 3 functions are run upon hitting submit. My final attempt which seems closest is adding the validateForm function at the bottom of my scripts to run all scripts but this did not seem to work. Hopefully something small I am overlooking, appreciate any help.
HTML:
<form name="registerkeys" form action="form.php" method="post" onsubmit="return validateForm();">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Phone Number: <input type="text" name="phonenumber"><br>
Information on Key: <input type="text" name="keyinfo"><br>
Password: <input type="password" name="password" id="password"></label><br>
Verify Password: <input type="password" name="passwordverify" id="passwordverify"><br>
Password Hint: <input type="text" name="passwordhint"><br>
<textarea rows="5" name="message" cols="30" placeholder="Comments:"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
Javascript:
function validateFill(){
var x=document.forms["registerkeys"]["first_name"].value;
if (x==null || x=="") {
alert("First name must be filled out");
return false;
}
var x=document.forms["registerkeys"]["last_name"].value;
if (x==null || x=="") {
alert("Last name must be filled out");
return false;
}
var x=document.forms["registerkeys"]["phonenumber"].value;
if (x==null || x=="") {
alert("Phone number must be filled out");
return false;
}
var x=document.forms["registerkeys"]["keyinfo"].value;
if (x==null || x=="") {
alert("Key info must be filled out");
return false;
}
var x=document.forms["registerkeys"]["pass1"].value;
if (x==null || x=="") {
alert("Password must be filled out");
return false;
}
var x=document.forms["registerkeys"]["passwordhint"].value;
if (x==null || x=="") {
alert("Password hint must be filled out");
return false;
}
}
function validateEmail()
{
var x=document.forms["registerkeys"]["email"].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");
return false;
}
}
function validatePassword(){
var password = document.getElementById("password").value;
var passwordverify = document.getElementById("passwordverify").value;
var ok = true;
if (password != passwordverify) {
alert("Passwords Do not match");
document.getElementById("password").style.borderColor = "#E34234";
document.getElementById("passwordverify").style.borderColor = "#E34234";
ok = false;
}
else {
alert("Passwords Match!!!");
}
return ok;
}
function validateForm(){
var a = validateFill();
var b = validateEmail();
var c = validatePassword();
return a && b && c;
}
Your validateFill() and validateEmail() function should return true at the end.
validateFill() only returns false if validation has not passed, but never true. You should add return true at the end of the function, outside of conditions.
validateEmail() returns false if email is invalid but you are missing the return true if email is valid.
Also, to prevent duplicate popups I suggest that you change your validateForm() to something like this:
function validateForm() {
var a = validateFill();
if (a) var b = validateEmail();
else var b = false;
if (a&&b) var c = validatePassword();
else var c = false;
return a && b && c;
}
So it only checks one function until it passes, and then checks the next.
validateFill() and validateEmail() should return true at the end (right now they return nothing if validation passed.
validatePassword() should return true instead of ok.
I have HTML page with javascript. In this, I have form which contains text for name and checkboxes. Below is the HTML form:
<form name="drugForm" action="form1.php" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="dname">
<pre>
<input type="checkbox" name="drug" value="id1">ID1 <input type="checkbox" name="drug" value="id2">ID2</br>
<input type="checkbox" name="drug" value="id3">ID3 <input type="checkbox" name="drug" value="id4">ID4</br>
</pre>
<input type="submit" value="Submit">
</form>
Below is the javascript for same:
<script>
function validateForm(){
var x=document.forms["drugForm"]["dname"].value;
//var y=document.drugForm.drug[0].value;
var y = new Array();
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
else if (Boolean(x))
{
alert("click any checkbox "+ y);
//alert("Working with boolean " + y);
return false;
}
}
</script>
Here, I want to check whether any checkbox is checked also along with name entry. But whenever I am trying to put for loop with y (array) in else if condition or anywhere in function, the code is not working and instead giving action directly.
My question, specifically, is how to check checkboxes, like did in if condition, is checked and how to get those values?
The code below validate when there's at least one checked box:
function validateForm(){
var x=document.forms["drugForm"]["dname"].value;
var y=document.drugForm.drug;
if (x==null || x=="") {
alert("First name must be filled out");
return false;
} else if (Boolean(x)) {
for (k=0;k<y.length;k++) {
if(y[k].checked) {
return true;
}
}
alert("Check one option at least");
return false;
}
}
There's another goog option in jquery as shown in another post.
Try this,
function validateForm(){
var x=document.forms["drugForm"]["dname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
else if (x)
{
if(!$('input:checkbox:checked').length)//check length of checked checkboxes
{
alert("click any checkbox ");
return false;
}
}
}
How to get alert for all empty field. In this bellow code, I am able to get alert for username field. how to get alert for all the fields.
JavaScript Code
function null_field(form_name, field_name) {
var field = document.forms[form_name][field_name].value;
if (field == null || field == "") {
alert("All Field Are Required");
return false;
}
}
Login Form
<form action="login_code.php" method="post" onSubmit="return null_field('login_form', 'username')" name="login_form">
<b>Username: </b><input type="text" name="username" class="field">
<b>Password: </b><input type="password" name="password" class="field">
<input type="submit" value="submit">
</form>
Create a function for the whole form instead:
function valid_form(form_name) {
var form = document.forms[form_name],
fields = form.elements, i = 0, l = fields.length;
for (; i < l; i++)
if (fields[i].value === "") {
alert("All Field Are Required");
return false;
}
return true;
}
For each field, you have to call the function. so, for each input tag, call onsubmit="not_null".
I think link will help you what you need. Hope you are looking for same
http://www.c-sharpcorner.com/blogs/8702/validation-summary-in-javascript.aspx
In raw javascript you could do the following:
function null_field(form_name)
{
for(i=0; i<document.forms[form_name].elements.length; i++){
if (document.forms[form_name].elements[i] == null ||document.forms[form_name].elements[i].value == "" || document.forms[form_name].elements.value == undefined)
{
alert("All Field Are Required");
return false;
}
}
return true;
}
If you need one single alert if there are any empty fields, you can use something like this:
function validate_fields(form_name) {
var has_empty_fields = false;
for (var field in document.forms[form_name].elements) {
if(field == null || field.value == "") {
has_empty_fields = true;
break;
}
}
if (has_empty_fields) {
alert("All Fields Are Required");
return false;
}
return true;
}