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.
Related
I have a form that uses javascript form validation and instead of listing each variable and what to validate it against per variable, I am trying to combine all of those variables into one variable and then have them validate against a singular list of elements.
I was trying initially to assign all of the input fields to a class and have them validate against the class instead of the name element but I could not get that to work so I am trying this.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["input1"].value;
var y = document.forms["myForm"]["input2"].value;
var z = x + y;
if (z == "123CODE" || z == "125CODE") {
return true;}
else if (z != "123CODE" || z != "125CODE") {
alert("Please enter a valid code"); return false;}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="input1">
<input type="text" name="input2">
<input type="submit" value="Submit">
</form>
</body>
</html>
This will be your javascript submit function:
DEMO
function validateForm() {
var x = document.forms["myForm"]["input1"].value;
var y = document.forms["myForm"]["input2"].value;
var z = x + y;
if (z == "123CODE" || z == "125CODE")
{
return true;
}
else
{
alert("Please enter a valid code");
return false;
}
}
Simultaneously if your code is not case sensitive you can write your if condition as -
if (z.trim().toLowerCase() == "123code" || z.trim().toLowerCase() == "125code")
if (z.search("123CODE")>0 || z.search("125CODE")>0)
{
}
you can write if statement like this if the search result is > 0 then condition will be true otherwise false.
<?php
if (isset($_POST['submit']) ) {
//send to database
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function validateForm() {
var usernameentry = document.forms["registrationform"]["username2"].value;
var passwordentry = document.forms["registrationform"]["password2"].value;
var nameentry = document.forms["registrationform"]["password2"].value;
var emailentry = document.forms["registrationform"]["email"].value;
var atpos = emailentry.indexOf("#");
var dotpos = emailentry.lastIndexOf(".");
if (usernameentry.length < 3 || username.length > 20){
alert("Username must be inbetween 4 and 20 characters");
return false;
}
else if (passwordentry.length < 3 || password.length > 20){
alert("Password must be inbetween 4 and 20 characters");
return false;
}
else if (nameentry.length < 3 || name.length > 45){
alert("Name must be inbetween 4 and 45 characters");
return false;
}
else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=emailentry.length || emailentry.length > 154) {
alert("Not a valid e-mail address");
return false;
}
else
{
return true;
}
}
</script>
</head>
<body>
<form name="registrationform" method="post" action="login.php" onsubmit="return validateForm();">
Name: <input type="text" name="name"/>
<br/>
<br/>
Email: <input type="text" name="email"/>
<br/>
<br/>
Username: <input type="text" name="username2"/>
<br/>
<br/>
Password: <input type="password" name="password2"/>
<br/>
<br/>
<input type = "submit" name = "submit" value = "submit" />
<br/>
<br/>
</form>
</body>
I want the contents of the if statement to run ONLY when the form has been validated with JavaScript, it runs regardless of whether the value returns is true or false.
I'm guessing what I need to do is similar to
if (isset($_POST['submit']) && onsubmit == true)
Obviously that's not right, but I don't know how to do it.
I know validating with php is a much more logical approach, but I need to demonstrate use of JavaScript.
You don't need to do that. When the form is validated, it will be sent to login.php
You can see this question HTML/Javascript: Simple form validation on submit
Also, there are a lot of libraries which could help you
http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
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
<script type='text/javascript'>
function required()
{
var empt = document.forms["form1"]["Name"].value;
if (empt == "")
{
alert("Please input a Value");
return false;
}
}
</script>
<form name="form1" method="" action="">
<input type="text" name="name" value="Name"/><br />
<input type="text" name="address line1" value="Address Line 1"/><br />
I have more than one input text field, each having their default value. Before I submit the form I have to verify whether all fields are filled. So far i got the javascript to check for null since different text boxes have different default value. How can I write a javascript to verify that user has entered data? I mean, the script must identify that input data is other than default and null.
If you are not using jQuery then I would simply write a validation method that you can be fired when the form is submitted. The method can validate the text fields to make sure that they are not empty or the default value. The method will return a bool value and if it is false you can fire off your alert and assign classes to highlight the fields that did not pass validation.
HTML:
<form name="form1" method="" action="" onsubmit="return validateForm(this)">
<input type="text" name="name" value="Name"/><br />
<input type="text" name="addressLine01" value="Address Line 1"/><br />
<input type="submit"/>
</form>
JavaScript:
function validateForm(form) {
var nameField = form.name;
var addressLine01 = form.addressLine01;
if (isNotEmpty(nameField)) {
if(isNotEmpty(addressLine01)) {
return true;
{
{
return false;
}
function isNotEmpty(field) {
var fieldData = field.value;
if (fieldData.length == 0 || fieldData == "" || fieldData == fieldData) {
field.className = "FieldError"; //Classs to highlight error
alert("Please correct the errors in order to continue.");
return false;
} else {
field.className = "FieldOk"; //Resets field back to default
return true; //Submits form
}
}
The validateForm method assigns the elements you want to validate and then in this case calls the isNotEmpty method to validate if the field is empty or has not been changed from the default value. it continuously calls the inNotEmpty method until it returns a value of true or if the conditional fails for that field it will return false.
Give this a shot and let me know if it helps or if you have any questions. of course you can write additional custom methods to validate numbers only, email address, valid URL, etc.
If you use jQuery at all I would look into trying out the jQuery Validation plug-in. I have been using it for my last few projects and it is pretty nice. Check it out if you get a chance. http://docs.jquery.com/Plugins/Validation
<form name="myForm" id="myForm" method="post" onsubmit="return validateForm();">
First Name: <input type="text" id="name" /> <br />
<span id="nameErrMsg" class="error"></span> <br />
<!-- ... all your other stuff ... -->
</form>
<p>
1.word should be atleast 5 letter<br>
2.No space should be encountered<br>
3.No numbers and special characters allowed<br>
4.letters can be repeated upto 3(eg: aa is allowed aaa is not allowed)
</p>
<button id="validateTestButton" value="Validate now" onclick="validateForm();">Validate now</button>
validateForm = function () {
return checkName();
}
function checkName() {
var x = document.myForm;
var input = x.name.value;
var errMsgHolder = document.getElementById('nameErrMsg');
if (input.length < 5) {
errMsgHolder.innerHTML =
'Please enter a name with at least 5 letters';
return false;
} else if (!(/^\S{3,}$/.test(input))) {
errMsgHolder.innerHTML =
'Name cannot contain whitespace';
return false;
}else if(!(/^[a-zA-Z]+$/.test(input)))
{
errMsgHolder.innerHTML=
'Only alphabets allowed'
}
else if(!(/^(?:(\w)(?!\1\1))+$/.test(input)))
{
errMsgHolder.innerHTML=
'per 3 alphabets allowed'
}
else {
errMsgHolder.innerHTML = '';
return undefined;
}
}
.error {
color: #E00000;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Validation</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var tags = document.getElementsByTagName("input");
var radiotags = document.getElementsByName("gender");
var compareValidator = ['compare'];
var formtag = document.getElementsByTagName("form");
function validation(){
for(var i=0;i<tags.length;i++){
var tagid = tags[i].id;
var tagval = tags[i].value;
var tagtit = tags[i].title;
var tagclass = tags[i].className;
//Validation for Textbox Start
if(tags[i].type == "text"){
if(tagval == "" || tagval == null){
var lbl = $(tags[i]).prev().text();
lbl = lbl.replace(/ : /g,'')
//alert("Please Enter "+lbl);
$(".span"+tagid).remove();
$("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Please Enter "+lbl+"</span>");
$("#"+tagid).focus();
//return false;
}
else if(tagval != "" || tagval != null){
$(".span"+tagid).remove();
}
//Validation for compare text in two text boxes Start
//put two tags with same class name and put class name in compareValidator.
for(var j=0;j<compareValidator.length;j++){
if((tagval != "") && (tagclass.indexOf(compareValidator[j]) != -1)){
if(($('.'+compareValidator[j]).first().val()) != ($('.'+compareValidator[j]).last().val())){
$("."+compareValidator[j]+":last").after("<span style='color:red;' class='span"+tagid+"'>Invalid Text</span>");
$("span").prev("span").remove();
$("."+compareValidator[j]+":last").focus();
//return false;
}
}
}
//Validation for compare text in two text boxes End
//Validation for Email Start
if((tagval != "") && (tagclass.indexOf('email') != -1)){
//enter class = email where you want to use email validator
var reg = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/
if (reg.test(tagval)){
$(".span"+tagid).remove();
return true;
}
else{
$(".span"+tagid).remove();
$("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Email is Invalid</span>");
$("#"+tagid).focus();
return false;
}
}
//Validation for Email End
}
//Validation for Textbox End
//Validation for Radio Start
else if(tags[i].type == "radio"){
//enter class = gender where you want to use gender validator
if((radiotags[0].checked == false) && (radiotags[1].checked == false)){
$(".span"+tagid).remove();
//$("#"+tagid").after("<span style='color:red;' class='span"+tagid+"'>Please Select Your Gender </span>");
$(".gender:last").next().after("<span style='color:red;' class='span"+tagid+"'> Please Select Your Gender</span>");
$("#"+tagid).focus();
i += 1;
}
else{
$(".span"+tagid).remove();
}
}
//Validation for Radio End
else{
}
}
//return false;
}
function Validate(){
if(!validation()){
return false;
}
return true;
}
function onloadevents(){
tags[tags.length -1].onclick = function(){
//return Validate();
}
for(var j=0;j<formtag.length;j++){
formtag[j].onsubmit = function(){
return Validate();
}
}
for(var i=0;i<tags.length;i++){
var tagid = tags[i].id;
var tagval = tags[i].value;
var tagtit = tags[i].title;
var tagclass = tags[i].className;
if((tags[i].type == "text") && (tagclass.indexOf('numeric') != -1)){
//enter class = numeric where you want to use numeric validator
document.getElementById(tagid).onkeypress = function(){
numeric(event);
}
}
}
}
function numeric(event){
var KeyBoardCode = (event.which) ? event.which : event.keyCode;
if (KeyBoardCode > 31 && (KeyBoardCode < 48 || KeyBoardCode > 57)){
event.preventDefault();
$(".spannum").remove();
//$(".numeric").after("<span class='spannum'>Numeric Keys Please</span>");
//$(".numeric").focus();
return false;
}
$(".spannum").remove();
return true;
}
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", onloadevents, false);
}
//window.onload = onloadevents;
</script>
</head>
<body>
<form method="post">
<label for="fname">Test 1 : </label><input type="text" title="Test 1" id="fname" class="form1"><br>
<label for="fname1">Test 2 : </label><input type="text" title="Test 2" id="fname1" class="form1 compare"><br>
<label for="fname2">Test 3 : </label><input type="text" title="Test 3" id="fname2" class="form1 compare"><br>
<label for="gender">Gender : </label>
<input type="radio" title="Male" id="fname3" class="gender" name="gender" value="Male"><label for="gender">Male</label>
<input type="radio" title="Female" id="fname4" class="gender" name="gender" value="Female"><label for="gender">Female</label><br>
<label for="fname5">Mobile : </label><input type="text" title="Mobile" id="fname5" class="numeric"><br>
<label for="fname6">Email : </label><input type="text" title="Email" id="fname6" class="email"><br>
<input type="submit" id="sub" value="Submit">
</form>
</body>
</html>
function hasValue( val ) { // Return true if text input is valid/ not-empty
return val.replace(/\s+/, '').length; // boolean
}
For multiple elements you can pass inside your input elements loop their value into that function argument.
If a user inserted one or more spaces, thanks to the regex s+ the function will return false.
<pre><form name="myform" action="saveNew" method="post" enctype="multipart/form-data">
<input type="text" id="name" name="name" />
<input type="submit"/>
</form></pre>
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("myform");
frmvalidator.EnableFocusOnError(false);
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Plese Enter Name");
</script>
before using above code you have to add the gen_validatorv31.js js file
For flexibility and other places you might want to validated. You can use the following function.
`function validateOnlyTextField(element) {
var str = element.value;
if(!(/^[a-zA-Z, ]+$/.test(str))){
// console.log('String contain number characters');
str = str.substr(0, str.length -1);
element.value = str;
}
}`
Then on your html section use the following event.
<input type="text" id="names" onkeyup="validateOnlyTextField(this)" />
You can always reuse the function.
i'm trying to make sure certain fields are not left blank in my form. it seems simple enough but for some reason it's not working. The alert is not showing, and return false is not working (it continues to post blank entries into my database) please help, what am i doing wrong. thank you!
the script:
function check(){
var name = getElementById('name');
var date = getElementById('date');
var pri = getElementById('pri');
var asapc = getElementById('asapc');
var asapn = getElementById('asapn');
var obr = getElementById('obr');
var obc = getElementById('obc');
var obn = getElementById('obn');
if (name.value == "" || date.value == "" || pri.value == "not" || asapc.value == "" || asapn.value == "" || obr.value == "" || obc.value == "" || obn.value == "") {
alert( "One or more fields were not filled out." );
return false ; }
return true;
}
The code:
<FORM ACTION="step2.php" METHOD="POST" onsubmit="check();">
<!-- fields here -->
<INPUT TYPE="submit" VALUE="CONTINUE">
access every element as document.getElementById... and in form tag write this onsubmit="return check();" instead if onsubmit="check();"
You are missing return here:
<FORM ACTION="step2.php" METHOD="POST" onsubmit="return check();">
You are missing (document) this is the correct syntax:
document.getElementById('id');
<script>
function check() {
var name = document.getElementById('name');
var date = document.getElementById('date');
if (name.value == "" || date.value == "") {
alert( "One or more fields were not filled out.");
return false;
}
}
</script>
and getElementByID means by ID not my tagName
<FORM ACTION="step2.php" METHOD="POST" onsubmit="return check();">
<input name="name" type="text" value="" id="name">
<input name="date" type="text" value="" id="date">
.....etc..
<INPUT TYPE="submit" VALUE="CONTINUE">
</FORM>