I am looking to do a Javascript email Id & checkbox validation. The validation is only working for the checkbox but not for the email id. how to correct it please?
codepen demo
function Validate()
{
var x=document.myform.email.value;
var atposition=x.indexOf("#");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-mail address");
return false;
}
return true;
}
function Validate(){
if(!validateForm()){
alert("Terms & Conditions!");
return false;
}
return true
}
function validateForm()
{
var c=document.getElementsByTagName('input');
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].checked){return true}
}
}
return false;
}
// this function is called on form submit and checks the return values of both the email and checkbox function. if either of them are false, you will be alerted.
function MainFunction(){
if(!validateCheckBox() || !ValidateEmail() ){
return false;
}
alert("the form has been successfully submitted");
return true
}
// this function validates the email
function ValidateEmail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("#");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-mail address");
return false;
}
return true;
}
// this function validates the checkbox
function validateCheckBox()
{
var c=document.getElementsByTagName('input');
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].checked){return true}
}
}
alert("Terms & Conditions!");
return false;
}
//you had two of the same named function before. also you were only checking the return of one of the functions. Above checks the return values of both of the functions. Hope this helps
<form name="myform" id="form_id" method="post" onsubmit="return MainFunction();">
<input type="text" name="email" class="subscribe_email_nf" placeholder="Enter Your Email Id..."> <br />
<input type="checkbox" name="option1" value="1">Accept Terms & Conditions<br />
<input type="submit" value="Submit Form">
</form>
Related
I am unable to stop the form from submitting when any of the inputs are blank. It's not erroring out, but it's also not stopping the submit. I have the function being called in the form submit input. It is under the onClick call.
JS File
function stopSubmit(){
var inDay = document.getElementById(indate).value;
var inType = document.getElementById(intype).value;
var inAmount = document.getElementById(inamount).value;
if (inDay == "") {
alert("Please select a date");
return false;
}
if (inType == "Select One"){
alert("Please select a frequency");
return false;
}
if (inAmount == ""){
alert("Please enter an amount");
return false;
}
else {
alert("Your form was submitted");
}
}
HTML File
<td>
<input type="submit" name="submitincome" value="submit" onclick="stopSubmit()">
</td>
Edit
Use the required attribute and you won't even need any JavaScript. See demo 2. for a functioning demo see this PLUNKER
OLD
Before each return false add e.preventDefault()
Demo (Does not function due to SO security measures)
function stopSubmit(e) {
var inDay = document.getElementById(indate).value;
var inType = document.getElementById(intype).value;
var inAmount = document.getElementById(inamount).value;
if (inDay == "") {
alert("Please select a date");
e.preventDefault();
return false;
}
if (inType == "Select One") {
alert("Please select a frequency");
e.preventDefault();
return false;
}
if (inAmount == "") {
alert("Please enter an amount");
e.preventDefault();
return false;
} else {
alert("Your form was submitted");
}
}
<form>
<td>
<input type="submit" name="submitincome" value="submit" onclick="stopSubmit()">
</td>
</form>
Demo 2 Use the required attribute
<!DOCTYPE html>
<html>
<head>
<style>
input {
display: block
}
</style>
</head>
<body>
<form id='inform' action='http://httpbin.org/post' method='post'>
<input id='indate' name='indate' required>
<input id='intype' name='intype' required>
<input id='inamount' name='inamount' required>
<input type="submit">
</form>
</body>
</html>
I was able to see where you doing the mistake, document.getElementById() takes in a string as the parameter but you happen to be passing an undefined variable
function stopSubmit(){
var inDay = document.getElementById('indate').value;
var inType = document.getElementById('intype').value;
var inAmount = document.getElementById('inamount').value;
if (inDay === "") {
alert("Please select a date");
return false;
}
if (inType == "Select One"){
alert("Please select a frequency");
return false;
}
if (inAmount === ""){
alert("Please enter an amount");
return false;
}
else {
alert("Your form was submitted");
}
}
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Validation Form</title>
<script type="text/javascript">
function validate()
{
var name_str=document.my_form.name.value;
if((name_str==null)||(name_str==""))
{
alert("Enter Name")
return false
}
var pwd_str=document.my_form.pwd.value;
if((pwd_str=="null")||(pwd_str==""))
{
alert("Enter Password")
return false
}
var repwd_str=document.my_form.repwd.value;
if((repwd_str=="null")||(repwd_str==""))
{
alert("ReEnter Password")
return false
}
if(pwd_str!=repwd_str)
{
alert("password must be same!");
return false
}
var age_str=document.my_form.age.value;
if((age_str=="null")||(age_str==""))
{
alert("enter age")
return false
}
if (isNaN(age_str))
{
alert("only numeric")
return false
}
var ph_str=document.my_form.ph.value;
if((ph_str=="null")||(ph_str==""))
{
alert("enter phone number")
return false
}
if (isNaN(ph_str))
{
alert("only numeric ph")
return false
}
if((ph_str.length<1)||(ph_str.length>10))
{
alert("Invalid length of ph")
return false
}
var email_str=document.my_form.email.value;
if((email_str=="null")||(email_str==""))
{
alert("enter email")
return false
}
var atposition=email_str.indexOf("#");
var dotposition=email_str.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length)
{
alert("Please enter a valid e-mail address")
return false
}
if ((!document.getElementById("a").checked)&&(!document.getElementById("b").checked))
{
alert("no button is selected");
return false
}
var i;
var group1 = document.my_form.hobby;
for (var i=0; i<group1.length; i++) {
if (group1[i].checked)
break;
}
if (i==group1.length)
return alert("No box is checked");
var group2 = document.getElementById.dd;
var index_opt = group2.options[group2.selectedIndex].value;
if(index_opt==Select)
{
alert("select course")
return false
}
}
</script>
</head>
<body bgcolor=aqua>
<center><h3>Application Form</h3></center>
<form name="my_form" onsubmit="validate()">
<strong>Name:   </strong>
<input type=text name=name><br/>
<strong>Password:   </strong>
<input type=password name=pwd><br/>
<strong>Retype Password:   </strong>
<input type=password name=repwd><br/>
<strong>Age:    </strong>
<input type=text name=age><br/>
<strong>Phone No:    </strong>
<input tupe= text name=ph><br/>
<strong>Email:    </strong>
<input type=text name=email><br/><br/>
<strong>Sex:    </strong>
<input type= "radio" name="gender" id="a" value="Male">Male    
<input type= "radio" name="gender" id="b" value="Female">Female    <br/><br/><br/>
<strong>Hobby:</strong>
<input type="checkbox"name= "hobby" id="1" value="singning">Singning<br/>
<input type="checkbox"name= "hobby" id="2" value="reading">Reading<br/>
<input type="checkbox"name= "hobby" id="3" value="tv">TV<br/>
<br/>
<strong>Country</strong>
<select name="mymenu" id="dd">
<option value ="Select">Select</option>
<option value ="India">India</option>
<option value ="China">China</option>
<option value ="SriLanka">SriLanka</option>
</select>
<input type="submit" value=Submit>
<input type="reset" value=Reset><br/>
</form>
</body>
</html>
The code doesn't validate from the radio button on wards. but if i run the radio button code and the other validation codes after the radio button code it works and when compiled in a single form it doesn't works. the drop down menu validation doesn't works at all. please help me. Thanks in advance.
It's not a problem with your radio button check. In your code, you can use one variable like x, that's the problem. kindly refer below code :
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length)
That above code x variable doesn't declare and doesn't assign any where in your code. So that line error occurred and terminated.
You change this x to email_str, As per your code should be like below,
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=email_str.length)
It's working fine.
First of all you should change your on submit Event like below
<form name="my_form" onsubmit="return validate(this.form)">
Here your complete Javascript
<script type="text/javascript">
function validate(form)
{
var name_str=document.my_form.name.value;
if((name_str==null)||(name_str==""))
{
alert("Enter Name")
return false
}
var pwd_str=document.my_form.pwd.value;
if((pwd_str=="null")||(pwd_str==""))
{
alert("Enter Password")
return false
}
var repwd_str=document.my_form.repwd.value;
if((repwd_str=="null")||(repwd_str==""))
{
alert("ReEnter Password")
return false
}
if(pwd_str!=repwd_str)
{
alert("password must be same!");
return false
}
var age_str=document.my_form.age.value;
if((age_str=="null")||(age_str==""))
{
alert("enter age")
return false
}
if (isNaN(age_str))
{
alert("only numeric")
return false
}
var ph_str=document.my_form.ph.value;
if((ph_str=="null")||(ph_str==""))
{
alert("enter phone number")
return false
}
if (isNaN(ph_str))
{
alert("only numeric ph")
return false
}
if((ph_str.length<1)||(ph_str.length>10))
{
alert("Invalid length of ph")
return false
}
var email_str=document.my_form.email.value;
if((email_str=="null")||(email_str==""))
{
alert("enter email")
return false
}
var email = document.getElementById('mail');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
var gender=document.my_form.gender.value;
if((gender=="null")||(gender=="")){
alert("Please Select Gender");
return false;
}
var i;
var group1 = document.my_form.hobby;
for (var i=0; i<group1.length; i++) {
if (group1[i].checked)
break;
}
if (i==group1.length){
alert("No box is checked");
return false;
}
var country=document.my_form.mymenu.value;
if(country=='Select'){
alert("You must Select your Country");
return false;
}
}
</script>
I'm trying to make a basic form validation but it's not working. I need to make it in such a way that after validation is passed, THEN ONLY it submits the form. I'm not sure how to do it though. My code is below.
[Important request]
** I'm actually pretty new to this so if possible I would like to get some concrete information/explanation concerning the DOM and how to manipulate it and style it (W3School is NOT helping) **
<form id="reg" method="POST" action="user.php" onsubmit="return validate()">
<label for="first">First Name: </label>
<input id="first" name="first" type="text" value="">
<label for="last">Last Name: </label>
<input id="last" name="last" type="text" value="">
<button type="submit">Register</button>
</form>
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false;
}else{
return true;
}
if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
return false;
}else{
return true;
}
}
Thanks
Try this:
function validate() {
var validForm = true;
var msg = '';
if (document.getElementById('first').value == "") {
msg += 'First Name Blank! ';
validForm = false;
}
if (document.getElementById('last').value == "") {
msg += 'Last Name Blank! ';
validForm = false;
}
if (!validForm) {
alert(msg);
}
return validForm;
}
Plunker example
Your validation function only validates the first name. Whether it's valid or not, the function returns before checking the last name.
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false; // WILL RETURN EITHER HERE ...
}else{
return true; // ... OR HERE
}
The return statement will exit the function at the point it appears, and other code after that is simply not executed at all.
Instead of doing it that way, keep a flag that determines whether the fields are all OK:
function validate(){
var isValid = true; // Assume it is valid
if(document.getElementById('first').value = ""){
alert('First Name Blank!');
isValid = false;
}
if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
isValid = false;
}
return isValid;
}
Here's the code to check for validation and stop it from submitting if it is incorrect data.
<form id="reg" method="POST" action="user.php">
<label for="first">First Name: </label>
<input id="first" name="first" type="text" value="">
<label for="last">Last Name: </label>
<input id="last" name="last" type="text" value="">
<button type="button" id="submit">Register</button>
</form>
document.getElementById('submit').onclick = function(){
if(validate()){
document.getElementById('reg').submit();
}
}
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false;
}else if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
return false;
}else{
return true;
}
}
All I have done here is made the submit button a regular button and handled submitting via JS, When an input of type submit is clicked the page will submit the form no matter what. To bypass this you can make it a regular button and make it manually submit the form if certain conditions are met.
Your javascript code can be:
document.getElementById('submit').onclick = function () {
if (validate()) {
document.getElementById('reg').submit();
}
}
function validate() {
if (document.getElementById('first').value == "") {
alert('First Name Blank!');
return false;
} else if (document.getElementById('last').value == "") {
alert('Last Name Blank!');
return false;
} else {
return true;
}
}
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;
}
HTML
<form name="myForm" id="myForm" onsubmit="return validate();" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type="text" name="name" id="name">
<textarea name="details" id="details"></textarea>
<input type="submit">
</form>
Javascript
function validate()
{
if(document.getElementById('details').value == '')
{
alert("Please Provide Details!");
document.getElementById('details').focus();
return false;
}
else if(document.getElementById('name').value == '')
{
alert("Please Provide Name!");
document.getElementById('name').focus();
return false;
}
else
return true;
}
OR
function validate()
{
if(document.myForm.details.value == '')
{
alert("Please Provide Details!");
document.myForm.details.focus();
return false;
}
else if(document.myForm.name.value == '')
{
alert("Please Provide Name!");
document.myForm.name.focus();
return false;
}
else
return true;
}
I have seen the codes from previous Stack Overflow but as I am using these and it is not working. Will anyone help to solve check empty Value on Textarea using Javascript but not jquery.
The Reference I have used
how to check the textarea content is blank using javascript?
And
How to check if a Textarea is empty in Javascript or Jquery?
I think you may have space problem on your textarea. Use a trim function to reduce that. Here is the example following. I hope it may solve your problem.
JavaScript Add this function
function trimfield(str)
{
return str.replace(/^\s+|\s+$/g,'');
}
And your JavaScript function
function validate()
{
var obj1 = document.getElementById('details');
var obj2 = document.getElementById('name');
if(trimfield(obj1.value) == '')
{
alert("Please Provide Details!");
obj1.focus();
return false;
}
else if(trimfield(obj2.value) == '')
{
alert("Please Provide Name!");
obj2.focus();
return false;
}
else
return true;
}
OR
function validate()
{
var obj1 = document.myForm.details;
var obj2 = document.myForm.name;
if(trimfield(obj1.value) == '')
{
alert("Please Provide Details!");
obj1.focus();
return false;
}
else if(trimfield(obj2.value) == '')
{
alert("Please Provide Name!");
obj2.focus();
return false;
}
else
return true;
}
And HTML with PHP
<form name="myForm" id="myForm" onsubmit="return validate();" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type="text" name="name" id="name">
<textarea name="details" id="details"></textarea>
<input type="submit">
</form>
You can use following jQuery to escape white spaces.
if($("#YourTextAreaID").val().trim().length < 1)
{
alert("Please Enter Text...");
return;
}