Check if an input is empty in form - javascript

i have a dynamic form so i have no idea which kind of input there will be every time and i need to handle that, so i've done something like this
<div id="repond-questionnaire" class="modal fade in" style="display: block;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Questionnaire de Test</h4>
</div>
<div class="modal-body" id="questionnaire_here">
<form method="post" id="questionnaire_form">
<div class="form-group">
<label for="text"><h3>Who are you?</h3></label>
<textarea type="text" name="80" class="form-control" rows="3" placeholder="Text..." required="" value=""></textarea>
</div>
<div class="form-group">
<label for="focusedInput"><h3>How old are you?</h3></label>
<input type="number" name="81" class="form-control" placeholder="Number..." required="" value="">
</div>
<div class="form-group">
<label for="focusedInput"><h3>What is your email?</h3></label>
<input type="email" name="82" class="form-control" placeholder="Email..." required="" value="">
</div>
<div class="form-group">
<label for="focusedInput"><h3>Do you like our website?</h3></label>
<div class="radio">
<label class="input-lg"><input type="radio" name="83" value="Oui">Oui</label>
</div>
<div class="radio">
<label class="input-lg"><input type="radio" name="83" value="Non">Non</label>
</div>
</div>
<input type="submit" name="sumbit" id="sumbit" value="Sumbit" class="btn btn-success"></form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="close" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$('#repond-questionnaire').on('click', '#sumbit', function() {
// here i need to check if all inputs are empty or not
//check if they have a valid input or not for security
//because after i will send everything and upload them to the data base
$.ajax({
url: "user/sumbit_answers.php",
method: "POST",
data: $('#questionnaire_form').serialize(),
beforeSend: function() {
$('#sumbit').val("Sumbiting...");
},
success: function(data) {
$('#questionnaire_form')[0].reset();
if (data == 'exit_failure') {
alert("something wrong happened");
} else {
$('#questionnaire_here').empty();
$('#questionnaire_here').html(data);
}
}
});
});
$('#repond-questionnaire').on('click', '#close', function(event) {
$('#questionnaire_here').empty();
});
});
</script>
and i'm obliged to do this because somehow the events of the form are blocked ( even though i'm not using event.preventdefault(), my form input are all like this
<input type='$type' name='$row[cid]' class='form-control' placeholder='$type...' required value=''>

Given that required attribute is already set at <input> elements within <form>, you can use .checkValidity() of <form> element.
Additionally you can include pattern attribute with RegExp [^\s]+ to require at least a single character at <input> elements. Adjust RegExp to meet requirement.
<form name="form">
<input name="input1" type="text" pattern="[^\s]+" required>
<input name="input2" type="text" pattern="[^\s]+" required>
<input type="submit">
</form>
<script>
document.forms.form.querySelector("[type=submit]")
.onclick = function() {
console.log(this.form.checkValidity());
// if (this.form.checkValidity()) { /* all <input> elements have `.value */ }
// else { /* all <input> elements do not have `.value */ }
}
</script>

var text_input=$("[type=text]");
var password_input=$("[type=password");
var radio_input=$("[type=radio]");
var checkbox_input=$("[type=checkbox]");
var select=$("<select>");
var textarea=$("<textarea>");
Then you have to do for loop for each one to check and apply your validation according to that field
Call ajax after validation (the following link will help you)
jQuery Form Validation before Ajax submit

Related

display one of two forms if button is clicked

I am in need of some help. I want to create a web page that has two buttons depending on which button is selected I want to display either form 1 or form 2. The next thing is if the user selects the button for form 1 I want to do form validation only for the selected form.
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
<button type="button" class="btn btn-outline-primary">show form 1</button>
<button type="button" class="btn btn-outline-primary">show form 2</button>
<br>
<form id="form1" class="needs-validation" novalidate>
<hr>
<p>THIS IS FORM 1</p>
<hr>
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationCustom01">form1 box 1</label>
<input type="text" class="form-control" id="validationCustom01" placeholder="form1 box 1" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-4 mb-3">
<label for="validationCustom02">form1 box 2</label>
<input type="text" class="form-control" id="validationCustom02" placeholder="form1 box 2" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form1</button>
</form>
<br>
<form id="form2" class="needs-validation" novalidate>
<hr>
<p>THIS IS FORM 2</p>
<hr>
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationCustom01">form2 box 1</label>
<input type="text" class="form-control" id="validationCustom01" placeholder="form1 box 1" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-4 mb-3">
<label for="validationCustom02">form2 box 2</label>
<input type="text" class="form-control" id="validationCustom02" placeholder="form1 box 2" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form2</button>
</form>
See if it fits your requirements.
I just added an event to the buttons that just flips the display property of the two forms.
For the validation, only the displayed form is validated, but once you validate a form it remains validated.
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
function toggle(i) {
let form1 = document.getElementById('form1');
let form2 = document.getElementById('form2');
if (i == 1) {
form1.style.display = 'none';
form2.style.display = 'block';
} else {
form1.style.display = 'block';
form2.style.display = 'none';
}
}
.row {
background: #f8f9fa;
margin-top: 20px;
}
.col {
border: solid 1px #6c757d;
padding: 10px;
}
<button type="button" id="btn1" class="btn btn-outline-primary" onclick="toggle(2)">show form 1</button>
<button type="button" class="btn btn-outline-primary" onclick="toggle(1)">show form 2</button>
<br><br>
<form id="form1" class="needs-validation" novalidate>
<hr>
<p>THIS IS FORM 1</p>
<hr>
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationCustom01">form1 box 1</label>
<input type="text" class="form-control" id="validationCustom01" placeholder="form1 box 1" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-4 mb-3">
<label for="validationCustom02">form1 box 2</label>
<input type="text" class="form-control" id="validationCustom02" placeholder="form1 box 2" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form1</button>
</form>
<form id="form2" class="needs-validation" style="display:none" novalidate>
<hr>
<p>THIS IS FORM 2</p>
<hr>
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationCustom01">form2 box 1</label>
<input type="text" class="form-control" id="validationCustom01" placeholder="form1 box 1" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-4 mb-3">
<label for="validationCustom02">form2 box 2</label>
<input type="text" class="form-control" id="validationCustom02" placeholder="form1 box 2" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form2</button>
</form>
For this kind of things i recommend you to use some framework by the way, something like vuejs, or also jquery for simple things.

Email validation for specific domain name

I have the following form. I want to validate the email field .it should only contain for domain name "#somename.com " when the user clicks submit.
The mail should only be validated when the check box is clicked to show the email field.
If the email is invalid i want to prevent submission
<form class="form-horizontal" id="rForm" data-toggle="validator" role="form">
<div class="form-group">
<div class="col-xs-offset-3 col-xs-8">
<label class="checkbox-inline col-xs-10">
<input type="checkbox" ID="chkbx"> Email
</label>
</div>
</div>
<div class="form-group email">
<div class="col-xs-offset-3 col-xs-8">
<div class="col-xs-8">
<input type="text" class="form-control " placeholder="Enter email">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-offset-3 col-xs-8">
<input type="reset" class="btn btn-default" id="rset" value="Reset">
<input type="submit" class="btn btn-primary" id="submit" value="Submit">
</div>
</div>
</form>
JS
$("#submit").on('keypress click', function(e){
e.preventDefault();
$('#chkbx').hide();
$('#chkbx').click(function () {
// This will show / hide your element accordingly
$('.email').toggle();
});
});
Checkout JavaScript RegEx to determine the email's domain (yahoo.com for example). You can use that and augment your example:
$('#chkbx').click(function() {
// This will show / hide your element accordingly
$('.email').toggle();
});
$("#submit").on('click', function(e) {
e.preventDefault();
if ($('#chkbx').is(':checked')) {
// https://stackoverflow.com/questions/3270185/javascript-regex-to-determine-the-emails-domain-yahoo-com-for-example
console.log(/#testdomain.com\s*$/.test($('#email_input').val()));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-horizontal" id="rForm" data-toggle="validator" role="form">
<div class="form-group">
<div class="col-xs-offset-3 col-xs-8">
<label class="checkbox-inline col-xs-10">
<input type="checkbox" ID="chkbx" checked>Email
</label>
</div>
</div>
<div class="form-group email">
<div class="col-xs-offset-3 col-xs-8">
<div class="col-xs-8">
<input id="email_input" type="text" class="form-control " placeholder="Enter email">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-offset-3 col-xs-8">
<input type="reset" class="btn btn-default" id="rset" value="Reset">
<input type="submit" class="btn btn-primary" id="submit" value="Submit">
</div>
</div>
</form>
Use the following function to test for your email.
EDIT:
You first need to add a name= and id= to your email input field.... So what you want to do is:
<input type="text" class="form-control " placeholder="Enter email" name="email" id="email">
and then do:
function testEmail(string) {
var regex = /.+#somename.com$/i;
return regex.test(string);
}
//testEmail("nope#test.com"); // false
//testEmail("what#somename.com.other"); //false
//testEmail("yeah#somename.com"); //true
//testEmail("#somename.com"); // false
$('form').submit(function(e){
var values = $('form').serialize();
if(!testEmail(values.email))
e.preventDefault();
// your submission code goes here.
})

ajax form not submitting handler expecting submit name attribute

I'm having a little problem getting a form to submit via ajax. I think it's one of two problems:
leads.py (which I am able to view, but do not have the ability to modify) is expecting a submit input name of name="submitButtonName" and because I am using e.preventDefault(); to disable normal form submitting the form is not being handled by the handler when submitted.
It could be possibly that the data being serialized is wrong, when i output it to console it looks like this which appears to be duplicated:
first_name=Frank&last_name=TheTank&email_addr=frank%40thetank.com&remarks=&first_name=Frank&last_name=TheTank&email_addr=frank%40thetank.com
any suggestions?
here is the full script:
<!-- Defines element markup -->
<dom-module id="landing-modal">
<template>
<div id="landing-modal" class="modal hide fade" tabindex="-1" role="dialog">
<div class="modal-body">
<p class=lead>
To view this listing, please provide us with some basic contact information...
</p>
<form class="form-horizontal lead-form" method="post" action="/leads/buy">
<div class="control-group">
<label class="control-label">Required Information</label>
</div>
<div class="control-group">
<label class="control-label">First Name</label>
<div class="controls">
<input type="text" name="first_name" value="" required="" class="style-scope lead-form">
</div>
</div>
<div class="control-group">
<label class="control-label">Last Name</label>
<div class="controls">
<input type="text" name="last_name" value="" required="" class="style-scope lead-form">
</div>
</div>
<div class="control-group">
<label class="control-label">Email</label>
<div class="controls">
<input type="email" name="email_addr" value="" required="" class="style-scope lead-form">
</div>
</div>
<div class="control-group">
<div class="controls">
<input style="display:none;" type="text" name="remarks" value="" />
<input type="reset" value="Reset" name="reset" class="btn">
<input class="btn btn-primary" type="submit" name="submitButtonName" value="Submit" />
</div>
</div>
</form>
</div>
</div>
</template>
<script>
$(document).on('submit', '.lead-form', function(e) {
$.ajax({
url: $('.lead-form').attr('action'), //gets the action url
type: $('.lead-form').attr('method'), //gets the form method post
data: $('.lead-form').serialize(), //creates the form submit date eg. FirstName=Mickey&LastName=Mouse
success: function(html) {
console.log($('.lead-form').serialize());
}
});
e.preventDefault(); //prevents the submit input from being submitted normally
});
Polymer({
is: 'landing-modal',
created: function() {},
ready: function() {},
attached: function() {},
detached: function() {},
attributeChanged: function(name, type) {}
});
</script>
</dom-module>
edit::
I tried to add
<input type="hidden" name="submitButtonName" />
<input class="btn btn-primary" type="submit" name="submit" value="Submit" />
which results in a 500 error in console
server side code:
if "submitButtonName" in kwargs:
errors = []
if not kwargs['first_name']:
errors.append("Please enter your first name.")
if not kwargs['last_name']:
errors.append("Please enter your last name.")
if not kwargs['email_addr']:
errors.append("Please enter your email address.")
if errors:
error_msg = "<ul>" + "".join([
"<li>"+x for x in errors
]) + "</ul>"
result['error_msg'] = error_msg
else:
save = True
if save:
# 'remarks' is an invisible field that can only get filled in by
# spam bots, so if there's a value in it, ignore the submission.
if kwargs['remarks']:
import sys
sys.stderr.write("Ignoring spam submission: %r\n" % ([mode,kwargs],))
else:
self.save_form(mode, kwargs)
raise cherrypy.InternalRedirect("/leads/thankyou/"+mode)
result.update(self.form.render(values))
if mode=="C":
result.update(self.cmaform.render(values))
if mode=="E":
result.update(self.contactform.render(values))
return result

How to hide content when a radio button is not checked and enable other content to be viewed

Basically i want to set up two radio buttons, one called 'Login' and the other called 'Register'
When the 'Login' radio button is checked i want the login section to be shown only and vise versa for the 'Register' button.
Any help is greatly appreciated
<div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h2 class="text-center"><img src="//placehold.it/110" class="img-circle"><br>Login</h2>
<div class="container">
<form role="form">
<label class="radio-inline">
<input type="radio" name="optradio">Login
</label>
<label class="radio-inline">
<input type="radio" name="optradio">Register
</label>
</form>
</div>
</div>
<div style="width:602px"class="modal-body row">
<form action="" method="post">
<div class="row">
<div style="padding-left:20px; padding-right:-20px class="col-sm-12 text-center">
<div class="form-group">
<label for="username">Username</label>
<input id="name" name="username" placeholder="Username" type="text" tabindex="1" class="form-control">
<div class="form-group">
<label for="password">Password</label>
<input id="password" name="password" placeholder="Password" type="password" tabindex="2" class="form-control">
<br>
<input class="form-control btn btn-success" name="submit" type="submit" value="Log In" id="submit" tabindex="4" >
<h4>Not a member? <label class="checkbox-Warning"><input type="checkbox" value=""></label></h4>
<!-- come back here and finished login and registration -->
<div class="text-center"><h3 style="text-align:center"><b>Register</b></h3></div>
<form id="register-form" action="index.php" method="post" role="form">
<div class="form-group has-feedback">
<label for="username">Username</label>
<span class="form-control-feedback input-validator-feedback" data-fieldname="username"></span>
<input type="text" name="newusername" id="newusername" tabindex="1" class="form-control validate-input" placeholder="Username" value="" autocomplete="off">
</div>
<div class="form-group has-feedback">
<label for="email">Email Address</label>
<span class="form-control-feedback input-validator-feedback" data-fieldname="email"></span>
<input type="text" name="newemail" id="email" tabindex="2" class="form-control validate-input" placeholder="Email Address" value="" autocomplete="off">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="newpassword1" id="password" tabindex="3" class="form-control" placeholder="Password" autocomplete="off">
</div>
<div class="form-group">
<label for="confirm-password">Confirm Password</label>
<input type="password" name="confirm-password1" tabindex="4" id="confirm-password1" class="form-control" placeholder="Confirm Password" autocomplete="off">
<br>
<input type="submit" name="register-submit" id="register-submit" tabindex="5" class="form-control btn btn-success" value="Register">
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
so all of the login should be visible when the login radio button is checked and all the register components should be hidden
I added an id to both of the buttons for document.getElementById.
<input type="radio" name="optradio" value="login" id="login-button" >
<input type="radio" name="optradio" value="register" id="register-button">
<script>
document.getElementById("login-button").addEventListener("click", function(){
document.querySelector('#login-div').style.display = 'initial';
document.querySelector('#register-div').style.display = 'none';
}, false);
document.getElementById("register-button").addEventListener("click", function(){
document.querySelector('#register-div').style.display = 'initial';
document.querySelector('#login-div').style.display = 'none';
}, false);
</script>
You could give the radio buttons different classes/id's, for example "registerbutton" and "loginbutton".
If you give the register part the class/id "register" and the login part the class/id "login", you can target them with jQuery.
You can put the following code between <script> tags.
$('.registerbutton').click( function() {
$('.login').css('display', 'none')
$('.register').css('display', 'inline-block')
});
$('.loginbutton').click( function() {
$('.login').css('display', 'inline-block')
$('.register').css('display', 'none')
});
jQuery works with css selectors, so '.loginbutton' is something with the class loginbutton. If you give the elements id's you should replace '.loginbutton' with '#loginbutton'.
I don't know if you've worked with jQuery yet, but if you haven't: don't forget to link a jQuery library. Don't forget it either when you have worked with it.
If you put this at the right before the closing </body> tag it should work.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$('.registerbutton').click( function() {
$('.login').css('display', 'none')
$('.register').css('display', 'inline-block')
});
$('.loginbutton').click( function() {
$('.login').css('display', 'inline-block')
$('.register').css('display', 'none')
});
</script>
The first <script> tag links the library with functions and the second tag calls the functions to make the thing work. If you give de html elements the right classes/id's.
Setup an event handler to notice if a radio button is ticked, and that responds to click events on the radio buttons.
With jQuery:
$("input[type=radio]").on('click', function () {
$(container).empty();
var newSection = $('input[type=radio]:checked').value; //Get name of the new section
$(container).append($('div.' + newSection));
});
On this click event, remove the html in the section and append the new section you'd like.
This answer doesn't necessarily tailor to your current code but is a concept for how you could approach it

Form gets submitted even if the required fields are left empty in angular JS

I am newbie to angular JS and i have created a form which is
HTML
<div data-ng-controller="ReservationController"
<form class="form-horizontal" role="form">
<div class="form-group">
<div class="col-sm-10">
<label>Guest Name</label>
<input type="text" class="form-control" placeholder="" ng-model="res_guest_name" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<label>Phone</label>
<input type="phone" class="form-control" ng-model="res_member_phone">
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<label>FAX</label>
<input type="phone" class="form-control" ng-model="res_member_fax">
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<label>Email</label>
<input type="email" class="form-control" ng-model="res_member_email" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-8 col-sm-10">
<button type="submit" class="btn btn-success" ng-click="res_save()">Save Changes</button>
</div>
</div>
</form>
</div>
CONTROLLER
function ReservationController($scope, $http, $cookieStore,$location,$filter) {
$scope.res_save = function()
{
var save_res ="https://pbg.com/save_form.html?contactid="+conId+"&token="+token+"&id="+$scope.resId+"&page=edit&guest_name="+$scope.res_guest_name+"&phone="+$scope.res_member_phone+"&fax="+$scope.res_member_fax+"&email="+$scope.res_member_email;
$http.get(save_res).success(function(response) {
alert('success');
});
}
}
My form gets submitted even after the required fields are left empty. it shows the error, then it gets submitted.
Obviously it will submit the form you didn't handled the submission of form.You just managed the errors :-)
Use ng-disabled="myForm.$invalid"
where myForm is the name field on form
<form class="form-horizontal" name="myForm" role="form">
<button type="submit" class="btn btn-success" ng-disable="myForm.$invalid" ng-click="res_save()">Save Changes</button>
If you don't want the button to be disable till then you can use
<button type="submit" class="btn btn-success" ng-click="res_save(myForm.$valid)">Save Changes</button>
And in controller
$scope.res_save = function(valid)
{
if(valid){
var save_res ="https://pbg.com/save_form.html?contactid="+conId+"&token="+token+"&id="+$scope.resId+"&page=edit&guest_name="+$scope.res_guest_name+"&phone="+$scope.res_member_phone+"&fax="+$scope.res_member_fax+"&email="+$scope.res_member_email;
$http.get(save_res).success(function(response) {
alert('success');
});
}
}
You are not checking for Form valid state before saving it , don't expect angular to magically stop saving when form is invalid.
You should look into the documentation for ng-submit. If you move the res_save function into an ng-submit on the form (and removed the ng-click on the submit input) it will validate against required fields, prevent execution of the function until they are valid.

Categories

Resources