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;
}
}
Related
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>
I want validation through jQuery. I have two fields name and email. email blank field validation is not working.
Here is my code,
<form>
Name : <input type="text" name="name" id="name"><br>
<span id="nameSpan"></span>
<br>
Email:<input type="email" name="email" id="email1"><br>
<span id="emailSpan"></span>
<br>
<input type="submit" id="submitBtn">
</form>
javascript
$(document).ready(function(){
var name = $("#name").val();
var email1 = $("#email1").val();
$("#submitBtn").on("click", function(){
if(name == '')
{
$("#nameSpan").html('Name is required');
return false;
}
else
{
$("#nameSpan").html('');
}
if(email1 == '')
{
$("#emailSpan").html('Email is required');
return false;
}
else
{
$("#emailSpan").html('');
}
});
});
Please guide me where am I wrong. Thanks in advance
You are checking values of inputs only once while page load. We need to check them everytime so lets move this part into onclick function.
$(document).ready(function(){
$("#submitBtn").on("click", function(){
var name = $("#name").val();
var email1 = $("#email1").val();
if(name == '')
{
$("#nameSpan").html('Name is required');
return false;
}
else
{
$("#nameSpan").html('');
}
if(email1 == '')
{
$("#emailSpan").html('Email is required');
return false;
}
else
{
$("#emailSpan").html('');
}
});
});
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I need to made a simple contact form validaton. I´m newbie in Javascript. I tried many tutorials for newbies, hovever, no one tutorial solved my situation, so I´m trying to made my own JS.
But it have two issues:
Form is sent though is empty, although incorrect validation
If validation is failed, it should return all errors on same time
$("#submit").click(function () {
if (validate()) {
$.post($("#contact-form").attr("action"),
$("#contact-form :input").serializeArray(),
function (info) {
$("#f1Err").empty();
$("#f1Err").html(info);
$("#f2Err").empty();
$("#f2Err").html(info);
$("#f3Err").empty();
$("#f3Err").html(info);
$("#f4Err").empty();
$("#f4Err").html(info);
clear();
});
$("#contact-form").submit(function () {
return false;
});
}
});
function validate() {
if ($("#f1").val() == "") {
$("#f1Err").html("Name is requied");
return false;
}
if ($("#f2").val() == "") {
$("#f2Err").html("E-mail is requied");
return false;
}
var re = /^(([^<>()[]\.,;:s#"]+(.[^<>()[]\.,;:s#"]+)*)|(".+"))#(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/igm;
if (!re.test($("#f2").val())) {
$("#f2Err").html("Incorrect e-mail format");
return false;
}
if ($("#f3").val() == "") {
$("#f3Err").html("Message subject is requied");
return false;
}
if ($("#f4").val() == "") {
$("#f4Err").html("Message is requied");
return false;
}
return (true);
}
function clear() {
$("#contact-form :input").each(function () {
$(this).val("");
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form autocomplete="off" id="contact-form" method="post" enctype="multipart/form-data" action="modules/process.php">
<div class="group">
<input type="text" class="move" name="f1" id="f1" /><span class="error" id="f1Err"></span>
<label>Name</label>
</div>
<div class="group">
<input type="text" class="move" name="f2" id="f2" /><span class="error" id="f2Err"></span>
<label>E-mail</label>
</div>
<div class="group">
<input type="text" class="move" name="f3" id="f3" /><span class="error" id="f3Err"></span>
<label>Message subject</label>
</div>
<div class="group">
<textarea type="text" class="move" name="f4" id="f4"></textarea><span class="error" id="f4Err"></span>
<label>Message</label>
</div>
<div class="submit-btn">
<input type="submit" value="SUBMIT" id="submit">
</div>
</form>
Thanks for any ideas.
Lets start with the first click function and the submit functionality, you haven't preventedDefault() to prevent the default method of the submit input you have provided, so you would need to preventDefault() of the event that is being sent in like so
$("#submit").click(function (e) {
e.preventDefault();
if (validate()) {
$.post($("#contact-form").attr("action"),
$("#contact-form :input").serializeArray(),
function (info) {
$("#f1Err").empty();
$("#f1Err").html(info);
$("#f2Err").empty();
$("#f2Err").html(info);
$("#f3Err").empty();
$("#f3Err").html(info);
$("#f4Err").empty();
$("#f4Err").html(info);
clear();
});
$("#contact-form").submit(function () {
return false;
});
}
});
as the method name shows, its "preventing the default behavior" from running. Next in your validation method, you are returing false after checking a field, so once that one of the validations fails, you are returning. maybe you should return a flag instead so like:
function validate() {
var flag = true;
if ($("#f1").val() == "") {
$("#f1Err").html("Name is requied");
flag = false;
}
if ($("#f2").val() == "") {
$("#f2Err").html("E-mail is requied");
flag = false;
}
var re = /^(([^<>()[]\.,;:s#"]+(.[^<>()[]\.,;:s#"]+)*)|(".+"))#(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/igm;
if (!re.test($("#f2").val())) {
$("#f2Err").html("Incorrect e-mail format");
flag = false;
}
if ($("#f3").val() == "") {
$("#f3Err").html("Message subject is requied");
flag = false;
}
if ($("#f4").val() == "") {
$("#f4Err").html("Message is requied");
flag = false;
}
return flag;
}
I think should solve your two biggest issues that you pointed out were wrong. (this is not necessarily the best implementation and variable names, i'll leave you to learn and improve on it)
I made a fiddle http://jsfiddle.net/3dnkvtb1. I set errors to false before validating each input, then for each check I set error to true if empty. Make sure to check the console for errors as you go. I added a console.log for each check. Then if no errors, send and clear your form.
$("#submit").click(function(event) {
event.preventDefault();
var hasError = false;
var re = /^(([^<>()[]\.,;:s#"]+(.[^<>()[]\.,;:s#"]+)*)|(".+"))#(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/igm;
if ($("#f1").val() == "") {
hasError = true;
$("#f1Err").html("Name is required");
}
console.log($("#f1").val());
if ($("#f2").val() == "") {
hasError = true;
$("#f2Err").html("E-mail is required");
}
console.log($("#f2").val());
if (!re.test($("#f2").val())) {
hasError = true;
$("#f2Err").html("Incorrect e-mail format");
}
console.log($("#f3").val());
if ($("#f3").val() == "") {
hasError = true;
$("#f3Err").html("Message subject is required");
}
console.log($("#f3").val());
if ($("#f4").val() == "") {
hasError = true;
$("#f4Err").html("Message is required");
}
console.log($("#f4").val());
if(!hasError){
console.log('no errors');
//send your form
$.ajax({
url: 'url-here',
type: 'post',
dataType: 'json',
action : 'submit',
data: $('#contact-form').serialize(),
success: function(response) {
console.log(response);
//do something
clear();
}
});
} else {
console.log('something is up');
}
function clear() {
$("#contact-form :input").each(function () {
$(this).val("");
});
}
});
When i post form only the title validation is working, the other two fields are not validated.
HTML
<form name="qaform" class="nice" method="POST" onsubmit="validateForm()" action="/ask/ask-question/">
<input type="hidden" id="id_selected_tags" name="tags">
<p>
<label for="id_title" class="inline-block">Title</label>
<input type="text" class="input-text inline-block" id="id_title" name="question_title">
</p>
<span id="error_title"></span>
<textarea id="id_question" name="question_description" class="full-width"></textarea>
<span id="error_body"></span>
<p>
<label for="id_tags" class="inline-block">Tags</label>
<input type="text" id="id_newstagbox" name="question_tags"/>
</p>
<span id="error_tags"></span>
<button class="btn btn-success" type="submit">Post your question</button>
</form>
JS
function validateForm()
{
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
return false;
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
return false;
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
return false;
}
}
After submitting the forms post successfully if title is present.
The stackoverflow form validation forced me to do this, its constantly saying me to add more text because my question contains mostly code.I know its good to provide more information about question but there are times when you can ask a question in few words without being too broad and then you have to rant about it to pass the FORM VALIDATION.
Just remove return false.modify it like below
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
var y=document.forms["myForm"]["farea"].value;
var z=document.forms["myForm"]["ftag"].value;
if (x==null || x=="")
{
document.getElementById('ern').innerHTML="*Please add a title*";
}
if (y==null || y=="")
{
document.getElementById('era').innerHTML="*Please add a desxription*";
}
if (z==null || z=="")
{
document.getElementById('ert').innerHTML="*Please add a tag*";
}
}
</script>
I prefer using jQuery:
$('#form').submit(function(e) {
var validated = true;
e.preventDefault();
//title validation
if ($('#id_title').val() == "") {
$('#error_title').html("*Please add a title*");
validated = false;
}
//body validation
if ($('#id_question').val() == "") {
$('#error_body').html("*Please add a description*");
validated = false;
}
//tag validation
if ($('#id_newstagbox').val() == "") {
$('#error_tags').html("*Please add a description*");
validated = false;
}
if(validated) {
$(this).unbind('submit').submit();
}
});
You just remove your return false inside each condition,
check this jsfiddle how it works if you remove return false line.
Note:Return false will stop your execution there
Remove the "return false" in the if clauses. This stops your function and the other if clauses wouldn´t get called.
just add 'return' keyword before validateform()
like this
<form name="qaform" class="nice" method="POST" onsubmit="return validateForm()" action="/ask/ask-question/">
Try making these 5 small changes to your validateForm method -
function validateForm() {
var valid = true; // 1
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
valid = false; // 2
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
valid = false; // 3
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
valid = false; // 4
}
return valid; // 5
}
i think the reason why it only validates the first one, is because you return false to exit the validate function, if you do the return false after all the if loops i think it will do what you want.
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;
}