Form validation just for one button - javascript

I'm new in web development. I have a form with two buttons, i have a javascript function to validate a form when it is submitted:
function validateForm() {
var freq = document.forms["schedulerForm"]["frequency"].value;
if(freq == null || freq ==""){
alert("Please select a frequency!");
return false;
}
var freqValue = document.forms["schedulerForm"]["frequencyValue"].value;
if (freqValue == null || freqValue == "") {
alert("Please enter a frequency value!");
return false;
}
var email = document.forms["schedulerForm"]["email"].value;
if (email == null || email == "") {
alert("Please add an email!");
return false;
}
}
And the Form: (Adapted for the question purpose)
<form method="post" id="schedulerForm" onsubmit="return validateForm()">
<div class="controls">
<select id="frequency" name="frequency" class="form-control">
<option value="">Select a Frequency</option>
<option value="seconds">Seconds</option>
<option value="minutes">Minutes</option>
<option value="hours">Hours</option>
</select>
</div>
<input type="text" name="frequencyValue" id="frequencyValue">
<input autocomplete="off" class="input" id="email" type="text" placeholder="Enter an email" data-items="8">
<input type="submit" class="btn btn-primary" name="btnStart" value="Start Scheduler" onclick="testScheduler('start')"/>
<input type="submit" class="btn btn-primary" name="btnStop" value="Stop Scheduler" onclick="testScheduler('stop')"/>
</form>
It is working, the function validation works, but i want to restrict this validation just for the first button and not for the other, I thought to take out the second button, but if i do that the form will not be submitted.
Any help will be appreciated!

If you do want both buttons to submit the form, but only 'start' to valid the form before submitting. Remove the onsubmit="return validateForm()" from the form and add it to the onclick of the button.
<input type="submit" class="btn btn-primary" name="btnStart" value="Start Scheduler" onclick="testScheduler('start'); return validateForm();"/>
There are other ways but this would be easiest.

Related

Javascript - A problem with the validation of my form

I have a problem with the validation script of my php form to send an email, and although it works very well to validate the form, when the user clicks on the "accept" button of the alert, the script does not block the action, and the form is sent anyway...
What am I doing wrong?
Thanks in advance!
HTML:
<div id="form">
<section>
<form action="send.php" method="post" accept-charset='UTF-8'>
<label for="email"></label>
<input id="email" type="email" name="email" maxlength="50">
<input type="hidden" name="privacy" value="blahblahblah"/>
<input id="submit" type="submit" name="submit" value="SEND" onclick="validate(this);">
</div>
</form>
</section>
</div>
SCRIPT (validation):
function validate () {
var email;
email = document.getElementById("email").value;
expresion = /\w+#\w+\.+\w/;
if(email === "") {
alert("You cannot submit this request. You must give us an email");
return false;
}
else if (email.length>50) {
alert("The maximum for email is 50 characters");
return false;
}
else if (!expresion.test(email)) {
alert("Check your information. The email format is not valid");
return false;
}
}
Change the event to onsubmit and put it on the form.
function validate () {
var email;
email = document.getElementById("email").value;
expresion = /\w+#\w+\.+\w/;
if(email === "") {
alert("You cannot submit this request. You must give us an email");
return false;
}
else if (email.length>50) {
alert("The maximum for email is 50 characters");
return false;
}
else if (!expresion.test(email)) {
alert("Check your information. The email format is not valid");
return false;
}
console.log('passed!');
}
<div id="form">
<section>
<form action="" method="post" accept-charset='UTF-8' onsubmit="return validate(this);">
<label for="email"></label>
<input id="email" type="email" name="email" maxlength="50">
<input type="hidden" name="privacy" value="blahblahblah"/>
<input id="submit" type="submit" name="submit" value="SEND">
</form>
</section>
</div>

login form validation javascript - value not present in $_POST

I am trying to validate the form with id's username and initial_password: The HTML portion is as:
<form name="myform" action="includes/logincontrol.php" method="POST" onsubmit="return validateForm()">
<div class="form-group"> <!-- User ID Field -->
<label id="user_name_error" >User ID:</label>
<input class="form-control" id="username" type="text" onfocusout ="validateUserName()"/>
</div>
<div class="form-group"> <!-- Password Field -->
<label id="password_error">Password: </label>
<input class="form-control" id="initial_password" type="password" onfocusout ="validatePassword()"/>
</div>
<div class="form-group"> <!-- Register -->
<p id="submit-error"></p>
<hr/>
<button class="btn btn-primary" id="login" type="submit">Login</button>
<input class="btn btn-danger" type="reset" value="Reset" onClick="clearfunc()"/>
<hr/>
<button type="button" class="btn btn-success" onclick="window.location.href = 'register_user.php'">Register</button>
<button type="button" class="btn btn-warning" onclick="window.location.href = 'changepw.php'">Change Password</button>
</div>
</form>
Java Script:
function validateUserName() {
var user_name_entered = document.getElementById('username').value;
if (user_name_entered.length === 0) {
producePrompt('User empty?', 'user_name_error', 'red');
document.getElementById('login').disabled = true;
return false;
}
producePrompt('User Name OK!', 'user_name_error', 'green');
document.getElementById('login').disabled = false;
return true;
}
function validatePassword() {
var password_entered = document.getElementById('initial_password').value;
if (password_entered.length === 0) {
producePrompt('Password empty?', 'password_error', 'red');
document.getElementById('login').disabled = true;
return false;
}
producePrompt('Password Entered!', 'password_error', 'green');
document.getElementById('login').disabled = false;
return true;
}
function producePrompt(message, promptLocation, color) {
document.getElementById(promptLocation).innerHTML = message;
document.getElementById(promptLocation).style.color = color;
}
I am unable to get the elements in $_POST array. Please help
You have to put name at inputs, to access them with $_POST.
<input name="usernameInput" class="form-control" id="username" type="text" onfocusout ="validateUserName()"/>
<?php
$username = $_POST['usernameInput'];
?>
If you want to see if the form is submited put a name in the type submit input and try this:
if (isset($_POST['submitButton']) {
$username = $_POST['usernameInput'];
#..etc
}

Javascript check if BOTH fields contain text

JS:
function check_form(){
var city = document.getElementById('sCity').value;
var region = document.getElementById('sRegion').value
if ((city != null || city !="") && (region != null || region !="")) {
alert('You can only search with a PostCode OR a City. Please remove either the City or PostCode.');
return false;
}
return true;
}
HTML:
<form action="<?php echo osc_base_url(true); ?>" method="get" class="nocsrf" onSubmit="return check_form()">
<fieldset>
<h3>City</h3>
<div class="row" id="wor1">
<input class="input-text" type="text" id="sCity" name="sCity" value="" />
</div>
</fieldset>
<fieldset>
<h3>Postcode</h3>
<div class="row" id="wor2">
<input class="input-text" type="text" id="sRegion" name="sRegion" value="" />
</div>
</fieldset>
<div class="actions">
<button type="submit">Apply</button>
</div>
</form>
FIDDLE
I need a way to check the two textfields above so that only ONE textfield can be text when the form is submitted. So if user types in a city + postcode, it will alert the user that the form can only take a postcode or a city.
I tried doing this myself but my code doesn't work...
Fix the condition to this:
if ((city != null && city !="") && (region != null && region !="")) {
Note the use of && for each of the two conditions instead of ||. This will make sure that the alert is shown when both fields are filled by the user.

Check if form is completed before activating submit button

I am creating a form where a user has to fill out several fields and then click sign up. However, I want JavaScript to check if the passwords match, and if they don't or a field is left empty to put the signup button into a disabled state with Bootstrap. However, nothing is working. Here is my code:
JSFIDDLE: http://jsfiddle.net/jbe65/
echo '
<h3>Don\'t have an account yet? Sign up now!</h3>
<form action="signup.php" method="post">
<input type="text" class="form-control" placeholder="Email" name="email" id="email">
<input type="password" class="form-control" placeholder="Password" name="pass" id="pass">
<input type="password" class="form-control" placeholder="Again" name="passver" id="passver">
<br><br>
<p id="submit">button class="btn btn-primary btn-block" type="submit">Sign Up/button></p>
</form>
<script>
var empty = "";
var email = $(\'#email\').val()\;
var pass = $(\'#pass\').val()\;
var passver = $(\'#passver\').val()\;
if (empty == email)
{
if (pass != passver)
{
document.getElementById("submit").innerHTML=\'<button class="btn btn-primary btn-block" type="submit" disabled="disabled">Sign Up</button>\';
}
}
</script>
';
I will suggest make the button lookalike disable (by css) and once all the cond pass can make it enable (by css)..
$(document).ready(function () {
$("#formid").on("submit", function (e) {
var empty = "";
var email = $('#email').val();
var pass = $('#pass').val();
var passver = $('#passver').val();
if (empty == email || pass !== passver)
{
alert("please enter valid email and password.");
e.preventDefault();
}
else
{
//u can call this in textbox blur also...
$("#sub").removeClass("disable");
}
});
});
Fiddle Demo
I'm assuming you are using PHP. If so, you can replace the echo statement with a closing PHP bracket ?> to escape the parser. It's generally easier to deal with.
To answer the question at hand, since you are using jQuery, there is no need to change the innerHTML of the p tag, just use the .prop() function, like so:
?>
<h3>Don't have an account yet? Sign up now!</h3>
<form action="signup.php" method="post">
<input type="text" class="form-control" placeholder="Email" name="email" id="email">
<input type="password" class="form-control" placeholder="Password" name="pass" id="pass">
<input type="password" class="form-control" placeholder="Again" name="passver" id="passver">
<p id="submit"><button class="btn btn-primary btn-block" type="submit">Sign Up</button></p>
</form>
<script>
var email = $('#email').val();
var pass = $('#pass').val();
var passver = $('#passver').val();
if ("" == email)
{
if (pass != passver)
{
$('#submit button').prop('disabled', true);
}
}
</script>
<?php
If you're using HTML5 , Put "Required" and then the submit button will not be loaded if there is an empty field Ex :

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