basic form validation not working - javascript

This simple form validation is not working and it's irritating me. Please let me know what is the problem. I have been trying to find a bug for almost two hours but can't find it. Please help me.
Take a look at code:
function validate()
{
if( $("#full_name").val() == "" )
{
alert( "Please provide your name!" );
$("#full_name").focus() ;
return false;
}
if( $("#email").val() == "")
{
alert( "Please provide your Email!" );
$("#email").focus() ;
return false;
}
if( $("#message").val() == "" )
{
alert( "Please Enter Message" );
return false;
}
return( true );
}
<div class="form">
<h2> Contact Us </h2>
<form name="c_form" action="#" method="post" onsubmit="return(validate());">
<div class="input">
<input type="text" name="full_name" id="full_name" placeholder="Full Name">
</div>
<div class="input">
<input type="text" name="email" id="email" placeholder="Email Address">
</div>
<div class="input textarea">
<textarea id="message" name="message" placeholder="Enter Message Here"></textarea>
</div>
<div class="input button">
<button id="button"> Send </button>
</div>
</form>
</div>

Why not using HTML5's native "required" attribute? Nowadays, most browsers will happily interpret it without problems. If you want to support older browsers, just use a library like h5validate, but (please) keep your html clean.
Take a look on the same form using those attributes. No JS, no DIV containers, just plain native Html:
input, textarea {
display:block;
margin-bottom: 5px;
}
<h2> Contact us without JS </h2>
<form name="c_form" action="#" method="post">
<input type="text" name="full_name" placeholder="Full Name" required>
<input type="email" name="email" placeholder="Email Address" required>
<textarea name="message" placeholder="Enter Message Here" required></textarea>
<button type="submit"> Send </button>
</form>

I made a few changes and it works. The following snippet:
Include jQuery.
Add all the contents inside $(function () {}).
function validate ()
{
if( $("#full_name").val() == "" )
{
alert( "Please provide your name!" );
$("#full_name").focus() ;
return false;
}
if( $("#email").val() == "")
{
alert( "Please provide your Email!" );
$("#email").focus() ;
return false;
}
if( $("#message").val() == "" )
{
alert( "Please Enter Message" );
return false;
}
return( true );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="form">
<h2> Contact Us </h2>
<form name="c_form" action="#" method="post" onsubmit="return(validate());">
<div class="input">
<input type="text" name="full_name" id="full_name" placeholder="Full Name">
</div>
<div class="input">
<input type="text" name="email" id="email" placeholder="Email Address">
</div>
<div class="input textarea">
<textarea id="message" name="message" placeholder="Enter Message Here"></textarea>
</div>
<div class="input button">
<button id="button"> Send </button>
</div>
</form>
</div>

I added an id of "c_form" to your html and removed the onsubmit property and used the following javascript code, which seemed to work. The key is calling ev.preventDefault();
$(document).ready(function () {
$("#c_form").submit(validate);
});
function validate(ev)
{
if( $("#full_name").val() == "" )
{
alert( "Please provide your name!" );
$("#full_name").focus() ;
ev.preventDefault();
return false;
}
if( $("#email").val() == "")
{
alert( "Please provide your Email!" );
$("#email").focus() ;
ev.preventDefault();
return false;
}
if( $("#message").val() == "" )
{
alert( "Please Enter Message" );
ev.preventDefault();
return false;
}
return true;
}

Related

The $_POST unable to retrieve data from the text field in the html file

There is a discovery.html file that links to a validate_signup.php file through action in the html form. When in the I am in the validate_signup.php and try to retrieve the values with $_POST['XXX'] of the text fields in the form namely regFName, regSName, regEName, regPName it returns an error that states undefined index XXX.
File directory(not sure if it could play a part)
Folder-- HTML, PHP, ect
HTML-- discovery.html, ect
PHP-- validate_signup.php, ect
I create an other html and php file that works similarly and in this example it worked.
HTML FROM:
<form class="modal-content animate" onsubmit="return validate();" action="../PHP/validate-signup.php" methode="post">
<div class="containerL">
<label><b>First name</b></label>
<input type="text" class="LoginFromPage" id="regFName" placeholder="Enter Frist name" name="regFName" required>
<label><b>Surname</b></label>
<input type="text" class="LoginFromPage" id="regSName" placeholder="Enter Surname" name="regSName" required>
<labelb>Email</b></labelb>
<input type="text" class="LoginFromPage" id="regEName" placeholder="Enter Email" name="regEName" required>
<label><b>Password</b></label>
<input type="password" id="regPName" placeholder="Enter Password" name="regPName"required>
<button type="submit">Register</button>
<button type="button" onclick="document.getElementById('id02').style.display='none'" id="cancelbtn">Cancel</button>
<div id="error_para" ></span>
</div>
</form>
PHP:
$password = $_POST["regPName"];
$email = $_POST["regEName"];
$surname = $_POST["regSName"];
$firstname = $_POST["regFName"];
JS-validate data
var error="";
var name = document.getElementById( "regFName" );
if(valPass() == false)
{
error = "Password must contain an UpperCase, LowerCase, Number and Symbol character";
document.getElementById( "error_para" ).innerHTML = error;
return false;
}
var email = document.getElementById( "regEName" );
if( email.value == "" || email.value.indexOf( "#" ) == -1 )
{
error = " You Have To Write Valid Email Address. ";
document.getElementById( "error_para" ).innerHTML = error;
return false;
}
else
{
return true;
}
the correct method not methode
<form class="modal-content animate" onsubmit="return validate();" action="../PHP/validate-signup.php" method="post">
<div class="containerL">
<label><b>First name</b></label>
<input type="text" class="LoginFromPage" id="regFName" placeholder="Enter Frist name" name="regFName" required>
<label><b>Surname</b></label>
<input type="text" class="LoginFromPage" id="regSName" placeholder="Enter Surname" name="regSName" required>
<labelb>Email</b></labelb>
<input type="text" class="LoginFromPage" id="regEName" placeholder="Enter Email" name="regEName" required>
<label><b>Password</b></label>
<input type="password" id="regPName" placeholder="Enter Password" name="regPName" required>
<button type="submit">Register</button>
<button type="button" onclick="document.getElementById('id02').style.display='none'" id="cancelbtn">Cancel</button>
<div id="error_para"></span>
</div>
</form>

validate popup, then open another popup

I am using bootstrap to create a popup signup form. Once the user clicks submit and it has been validated I want to close that popup and open another saying thank you. I have tried using .modal('show') in popupvalidation.js but that did not seem to work. All it did was open both at the same time.
Here is the code:
index.php
<form name="popup" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" onsubmit="return popupValidation();" method="post">
<div class="row">
<input name="firstName" type="text" class="form-control" id="inputFirstName" placeholder="First Name">
<input name="lastName" type="text" class="form-control" id="inputLastName" placeholder="Last Name">
</div>
<div class="row">
<input name="email" type="email" class="form-control" id="inputEmail" placeholder="youremail#email.com">
</div>
<div class="row">
<input name="password" type="password" class="form-control" id="inputPassword" placeholder="password">
</div>
<div class="row">
<input name="repeatPass" type="password" class="form-control" id="retypePassword" placeholder="Retype password">
</div>
<div class="row">
<input name="trainer" type="checkbox"/> Sign up as trainer
</div>
<div class="modal-footer popup-footer">
<p id="error">Please make sure all fields are filled out</p>
<input type="submit" class="btn btn-default submit" value="Register">
</div>
</form>
popupvalidation.js
function popupValidation() {
var fname = document.forms["popup"]["firstName"].value;
var lname = document.forms["popup"]["lastName"].value;
var pass = document.forms["popup"]["password"].value;
var repass = document.forms["popup"]["repeatPass"].value;
var email = document.forms["popup"]["email"].value;
if (fname==null || fname=="") {
document.getElementById("inputFirstName").focus();
document.getElementById("error").innerHTML= 'Please enter your First Name';
document.getElementById("error").style.display = 'block';
return false;
}
if (lname==null || lname=="") {
document.getElementById("inputLastName").focus();
document.getElementById("error").innerHTML= 'Please enter your Last Name';
document.getElementById("error").style.display = 'block';
return false;
}
if (email==null || email=="") {
document.getElementById("inputEmail").focus();
document.getElementById("error").innerHTML= 'Please enter a valid email';
document.getElementById("error").style.display = 'block';
return false;
}
if (pass==null || pass=="") {
document.getElementById("inputPassword").focus();
document.getElementById("error").innerHTML= 'Please enter a password';
document.getElementById("error").style.display = 'block';
return false;
}
if (repass==null || repass=="") {
document.getElementById("retypePassword").focus();
document.getElementById("error").innerHTML= 'Please retype password';
document.getElementById("error").style.display = 'block';
return false;
}
if (repass!=pass) {
document.getElementById("retypePassword").focus();
document.getElementById("error").innerHTML= 'Passwords do not match';
document.getElementById("error").style.display = 'block';
return false;
}
}

Execute PHP Submit button Only if Javascript is true

I am trying to execute the mysql query using PHP form. Below is the form
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="signup.css" type="text/css">
<script type="text/javascript" src="form_val.js"></script>
<title>Untitled Document</title>
</head>
<body bgcolor="#0ca3d2">
<div align="right">
<h2>Go back</h2>
</div>
<div class="form-style-10">
<h1>Sign Up Now!<span>Sign up and tell us what you think of the site!</span></h1>
<form action="#" method="post" name="myForm" onSubmit="CheckTerms()">
<div class="section"><span>1</span>First Name & Address</div>
<div class="inner-wrap">
<input type="text" name="First_Name" placeholder="Enter First Name" id="fname">
<label id="error" style="color:red"></label>
<input type="text" name="Last_Name" placeholder="Enter last Name"/>
<label id="error_l" style="color:red"></label>
<select name="gender">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
<div class="section"><span>2</span>Email </div>
<div class="inner-wrap">
<input type="text" name="Email_i" placeholder="enter email here" id="e_mail" />
<label id="error_e" style="color:red"></label>
<button type="button" name="validate" onclick="loadDoc(this.value)">Validate</button>
<div id="check"></div></div>
<div class="section"><span>3</span>Passwords</div>
<div class="inner-wrap">
<input type="password" name="pass" placeholder="Must be 6 to 15 characters" id="Pass" onBlur="PassCheck()" />
<label id="error_p" style="color:red"></label>
<input type="password" name="repass" placeholder="Retype Password" id="RePass"/>
<label id="error_rp" style="color:red"></label>
<span class="privacy-policy">
<input type="checkbox" name="terms" value="value1" id="check_box">Agree to Terms and Conditions
</span>
<input type="submit" name="signup" value="Register" id="sub_button">
<label id="error_lable" style="color:red"></label>
</div>
</form>
</div>
</body>
I have the below form validation in Javascript,
function CheckTerms(){
var letter = /^[a-zA-Z ]*$/;
if(document.myForm.First_Name.value.match(letter) && document.myForm.First_Name.value =="")
{
document.getElementById("error").innerHTML = "* Please Provide First Name";
document.myForm.First_Name.focus();
return false;
}
if(document.myForm.Last_Name.value.match(letter) && document.myForm.Last_Name.value =="" )
{
document.getElementById("error_l").innerHTML = "* Please provide your Last name!";
document.myForm.Last_Name.focus() ;
return false;
}
var email =/^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if(document.myForm.Email_i.value.match(email) && document.myForm.Email_i.value=="")
{
document.getElementById("error_e").innerHTML = "* Please provide your EMAIL!";
document.myForm.Email_i.focus() ;
return false;
}
var min = 6;
var max = 15;
if(document.myForm.pass.value.length < min || document.myForm.pass.value.length > max)
{
document.getElementById("error_p").innerHTML = "Password Should be betweeen 6 to 15 characters";
document.myForm.pass.focus() ;
return false;
}
var pass = document.getElementById("Pass").value;
var re = document.getElementById("RePass").value;
if(pass != re)
{
document.getElementById("error_rp").innerHTML = "Password do not match";
return false;
}
if(document.getElementById("check_box").checked == false)
{
document.getElementById("error_lable").innerHTML = "Please Check";
return false;
}}
<?php
session_start();
include "config.php";
if(isset($_POST['signup']))
{
// my logic here
}
?>
but the problem is, even the javascript returns the error, clicking the submit button , executes PHP script resulting the data entry into database. I want to stop form submission if any of the javascript error exists.
You are not returning the boolean in the event even though you are doing it in the function. onSubmit receives true by default and submits it.
Change
onsubmit="CheckTerms()"
to
onsubmit="return CheckTerms()"

Registration and validation form with angularjs

I have a problem with a registration form on angularjs, I want to controle the form before submit and how can i save user data in text file or json (any solution for saving data), I did not manage to do it.
For more information, I am working on a project : Interface for ReafctorErl public server - javascript (angular based).
registration.html :
<div class="register">
<div class="box">
<h4> Sign Up</h4>
<p> Enter your personal details below: </p>
</br>
<form role="frmRegister" name="frmRegister" ng-submit="register()" >
<div class="form-group">
<input class="form-control" type="text" id="fullname" placeholder="Full Name" ng-model="credentials.fullname"/>
</div>
<div class="form-group">
<input class="form-control" type="text" id="organisation :" placeholder="Organisation" ng-model="credentials.organisation" />
</div>
<div class="form-group">
<input class="form-control" type="text" id="address :" placeholder="Address" ng-model="credentials.address" />
</div>
<p> Enter your account details below: </p>
<div class="form-group">
<input class="form-control" type="email" id="email" placeholder="Email" ng-model="credentials.email" />
</div>
<div class="form-group">
<input class="form-control" type="text" id="username" placeholder="Username" ng-model="credentials.username" />
</div>
<div class="form-group" >
<input class="form-control" type="password" id="password" placeholder="Password" ng-model="credentials.password" />
</div>
<div class="form-group" >
<input class="form-control" type="password" id="password_again" placeholder="Password again" ng-model="credentials.password_again" />
</div>
<div class="form-actions">
Back
<button type="submit" class="btn btn-primary" onclick="return verif();">Submit</button>
</div>
</br>
</form>
</div>
</div>
<script language="javascript">
function verif(){
if (document.getElementById('password').value != document.getElementById('password_again').value) {
document.getElementById('password_again').setCustomValidity('Passwords must match.');
}
else {
document.getElementById('password_again').setCustomValidity('');
}
}
</script>
the controller file :
'use strict';
function RegisterCtrl($scope, reg) {
var credentials = {
fullname: "",
organisation: "",
address: "",
email: "",
username: "",
password: "",
password_again: ""
};
$scope.credentials = credentials;
$scope.restricted = window.restrictedMode;
$scope.register = function() {
if( $scope.frmRegister.fullname.length<1 ) {
alert("Full Name required!");
return false;
}
if( $scope.credentials.organisation.length<1 ) {
alert("Organisation required!");
return false;
}
if( $scope.credentials.address.length<1 ) {
alert("Address required!");
return false;
}
if( $scope.credentials.email.length<1 ) {
alert("Email required!");
return false;
}
if( $scope.credentials.username.length<1 ) {
alert("Username required!");
return false;
}
if( $scope.credentials.password.length<3 ) {
alert("Password required!");
return false;
}
if( $scope.credentials.password_again.length<3 ) {
alert("Password again required!");
return false;
}
reg.register($scope.credentials.fullname, $scope.credentials.organisation, $scope.credentials.address,
$scope.credentials.email, $scope.credentials.username, $scope.credentials.password, $scope.credentials.password_again, true);
};
}
Service file is :
'use strict';
/*just trying todo something here */
angular.module('referl.services').service('reg', function($q, $http, $location, $rootScope, $window) {
var reg = {
register: function(fullname, organisation, address, email, username, password, password_again, navigateOnSuccess) {
var parameters = {
fullname: fullname,
organisation: organisation,
address: address,
email: email,
username: username,
password: password,
password_again: password_again
};
$http.get("api/register", {params: parameters}).success(function(response) {
if(response.error) {
alert(response.error);
} else {
alert("Success");
}
});
}
};
$rootScope.reg = reg;
return reg;
});
Any help please ??
Thank you!
Better to follow https://docs.angularjs.org/guide/forms for html page that will reduce your angular controller code. and you can focus on service validation
Follow Binding to form and control state section of above link how to validate form.
To your input text's u can use: ng-pattern and attribute required
<form name="exampleForm" class="form-horizontal">
<div class="form-group">
<input class="form-control" type="text" id="fullname" placeholder="Full Name" ng-model="credentials.fullname" ng-pattern="INSERT PATTERN" required/>
</div>
</form>
to find patterns you can see here:
HTML5 pattern
and for valite the whole form
<button class="btn btn-primary" ng-click="myFunction()" ng-disabled="exampleForm.$invalid">Button</button>

How to check if function returns true

I have a web form that submits if my function validate form returns true in that function i wrote an if statement that if another function called usernamecheck returns true then return the validateform function true. I dont want the form to submit unless you click the button to check the username. I know i didnt write this the best way i hope you understand
<!-- Signup Form -->
<form name='signup' action="subscription.php" onsubmit="return validateForm();" method="post" >
<input type="text" id="signupUsername" name="signupusername" placeholder="Business Name" tabindex=1 required>
<input type="password" id="signupPassword" placeholder="Password" name="signuppassword" tabindex=2 required> <br>
<input type="text" id="ownerName" placeholder="Owner's Name" name="ownername" tabindex=3 required>
<input type="email" id="signupEmail" placeholder="Email" name="signupemail" tabindex=4 required>
<input type="tel" id="signupphoneNumber" placeholder="Phone Number" name="signupphonenumber" tabindex=5 required>
<input type="image" id="signupSubmit" src="images/signupBtn.jpg">
<input type="text" id="city" placeholder="City" name="city" tabindex=6>
<input type="text" id="state" placeholder="State" name="state" tabindex=7>
This is the button that you click to check your username if it exists
<input type="button" id='check' value="Check It">
//
</form>
<script type="text/javascript">
Below there is the function where if you click the button above it checks the function usernamecheck
$(function() {
$( "#check" ).click(function() {
return usernamecheck();
});
});
Below is the validateForm function where if usernamecheck returns true it returns true as well and submits the form
function validateForm()
{
if(usernamecheck() && $("#signupUsername").val().length < 4) {
return true;
}
}
function usernamecheck() {
$.post( "checkusername.php", { username: $("#signupUsername").val() })
.done(function( data ) {
result = JSON.parse(data);
if(result["status"]== "Username is taken")
{
alert("username is taken");
return false;
}
else if(result["status"]== "Username is Available") {
alert("username is Available");
return true;
}
else {
alert('You did not check the username');
}
});
}
</script>
<!-- Map Logo -->
<img src='images/map.jpg' id="map" class='menuitems'>
<!-- About Us Logo -->
<img src='images/aboutus.jpg' id="aboutus" class='menuitems'>
<!-- People Logo -->
<img src='images/people.jpg' id="people" class='menuitems'>
</div>
</div>
</div>
</body>
</html>

Categories

Resources