Validation for textbox by using checkbox - javascript

This is my code:
<input type="password" id="centraPassword" placeholder="Enter Centra Password" class="form-control" ng-model="centraPassword" />
<label>
<input type="checkbox" ng-model="centrapasswordcheck" >
I have a Centra Travels password
</label>
<button type="submit" class="btn btn-info" ng-disabled="continueEmailButton" id="btnContinue" ng-click="ContinueDetails()">Continue</button>
This is my angularjs Code:
$scope.ContinueDetails = function () {
if ($scope.centrapasswordcheck == true)
{
if ($scope.centraPassword == '' || $scope.centraPassword == null) {
alert("please enter your password")
return;
}
}
}
In the above code when I click the Continue button, first check the checkbox checked or not after it will check enter the password or not.

var module = angular.module('myApp', []);
module.controller('myCtrl', function($scope) {
$scope.centrapasswordcheck = true;
$scope.ContinueDetails = function () {
if ($scope.centrapasswordcheck == true) {
if ($scope.centraPassword == '' || $scope.centraPassword == null) {
alert("please enter your password 1");
}
else {
alert("Password Validated");
}
} else {
alert('Please Check Checkbox');
}
alert('Coming out of the fuction');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<input type="password" id="centraPassword" placeholder="Enter Centra Password" class="form-control" ng-model="centraPassword" />
<label>
<input type="checkbox" ng-model="centrapasswordcheck" >
I have a Centra Travels password
</label>
<button type="submit" class="btn btn-info" ng-disabled="!centrapasswordcheck" id="btnContinue" ng-click="ContinueDetails()">Continue</button>
</body>
Check Once Is it what you want or something else
Remove alerts ands code what you want

Related

how to get external form validation to work with jQuery

Okay, I'm trying to get a contact form to work and it is, sort of. The data is passing through, but I can't get the jQuery to work. If I type in two different email addresses it doesn't catch it. Here is the relevant code I used:
HTML
<aside>
<form action="sendmail.php" method="post" name="contact_form" id="contact_form">
<fieldset>
<legend>sign up now!</legend><br>
<p>Sign up for my email list and get a free mini coloring book!</p><br>
<img src="Images/minicoloirngbook.jpg" alt="mini coloring book"><br>
<label for="name"> Name:</label>
<input type="text"name="name" id="name" required><span>*</span><br>
<label for="email">Email Address:</label>
<input type="email" name="email" id="email" required><span>*</span><br>
<label for="verify">Verify Email:</label>
<input type="email" name="verify" id="verify" required> <span>*</span><br>
<div id="buttons">
<input type="submit" id="submit" value="Sign Up">
</div>
</fieldset>
</form>
</aside>
and here is the Javascript:
$("#contact_form").submit(event => {
let isValid = true;
// validate the first name entry
const name = $("#name").val().trim();
if (name == "") {
$("#name").next().text("This field is required.");
isValid = false;
} else {
$("#name").next().text("");
}
$("#name").val(name);
// validate the email entry with a regular expression
const emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
const email = $("#email").val().trim();
if (email == "") {
$("#email").next().text("This field is required.");
isValid = false;
} else if ( !emailPattern.test(email) ) {
$("#email").next().text("Must be a valid email address.");
isValid = false;
} else {
$("#email").next().text("");
}
$("#email").val(email);
// validate the verify entry
const verify = $("#verify").val().trim();
if (verify == "") {
$("#verify").next().text("This field is required.");
isValid = false;
} else if (verify !== email) {
$("#verify").next().text("Must match first email entry.");
isValid = false;
} else {
$("#verify").next().text("");
}
$("#verify").val(verify);
// prevent the submission of the form if any entries are invalid
if (isValid == false) {
event.preventDefault();
}
}),
I think that the answer is probably something really simple that I can't see and would appreciate your help in figuring it out.
This should do it. Here is the jsfiddle if you like to play with the code: https://jsfiddle.net/bogatyr77/xk6ez3aq/7/
$("form").submit(function(e) {
var name = $("#a").val();
if (name == "") {
$("#nameerror").text("This field is required.");
alert('false');
} else {
alert('true');
$("#nameerror").remove();
}
//email1
var emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
const email = $("#b").val();
if (email == "") {
$("#email1error").text("This field is required.");
isValid = false;
} else if (!emailPattern.test(email)) {
$("#email1error").text("Must be a valid email address.");
isValid = false;
} else {
$("#email1error").remove();
}
//eamil 2
var verify = $("#c").val();
if (verify == "") {
$("#email2error").text("This field is required.");
isValid = false;
} else if (verify !== email) {
$("#email2error").text("Must match first email entry.");
isValid = false;
} else {
$("#email2error").remove();
}
if (isValid == false) {
event.preventDefault();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="javascript:alert('ok')">
<label for="name"> Name:</label>
<input type="text" name="name" id="a"><span>*</span>
<div id="nameerror"></div><br>
<label for="email">Email Address:</label>
<input type="text" name="email" id="b"><span>*</span>
<div id="email1error"></div><br>
<label for="verify">Verify Email:</label>
<input type="text" name="verify" id="c"> <span>*</span>
<div id="email2error"></div><br>
<input type="submit" value="submit" />
</form>
<div></div>

The id-selector does not work within php

my javascript won't respond to my id-tag within php code:
else {
echo '<form = "nav-login" method="post" onsubmit="return noEmptyUserFields();" action="includes/login.inc.php">
<input type="text" id="uidz" name="uid" placeholder="Username/e-mail">
<input type="password" id="pwdz" name="pwd" placeholder="password">
<button type="submit" name="submit">Login</button>
</form>
Sign up';
}
But it responds to my javascript which is outside of the php which looks like this:
<form class="signup-form" method="post" onsubmit="return noEmptyUserFields();" action="includes/signup.inc.php">
<input type="text" id="first" name="first" placeholder="Firstname">
<input type="text" id="last" name="last" placeholder="Lastname" >
<input type="email" id="email" name="email" placeholder="E-mail" >
<input type="text" id="uid" name="uid" placeholder="Username" >
<input type="password" id="pwd" name="pwd" placeholder="Password" ></p2>
<button type="submit" name="submit">Sign up</button></form>
How come it won't respond to the id-selector within php?
I have included <script src="includes/javascript.js"></script>
on both.
My javascript looks like this (noEmptyLoginFields) :
if (email.trim().length < 1)
{
alert('Email must be filled out');
return false;
}
else if(pwd.trim().length < 6)
{
alert('Password must contain atleast 6 characters');
return false;
}
else if (first.trim().length < 1)
{
alert('First name must be filled out');
return false;
}
else if (last.trim().length < 1)
{
alert('Last name must be filled out');
return false;
}
else if (uid.trim().length < 1)
{
alert('Username must be filled out');
return false;
}
else return true;
}
function noEmptyLoginFields()
var uidz = document.getElementById('uidz').value;
var pwdz = document.getElementById('pwdz').value;
if (uidz.trim().length < 1)
{
alert('Username and password must be filled out!');
return false;
}
else if(pwdz.trim().length < 1)
{
alert('Username and password must be filled out!');
return false;
}
}
You seem to be using the same function name for both form validations, which is causing the error. I advise you to handle form validation purely in javascript using event handlers:
document.querySelector("#formId").addEventListener("submit", function() {
// if(...) return false;
});

How to print error message under respective input field using javascript validation in php [closed]

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 6 years ago.
Improve this question
How to print error message under respective input field if left empty and error message must be removed when filled, how to proceed further i have not used javascript for validation earlier.
script code
function validateForm() {
var a = document.forms["student_reg"]["name"].value;
if (a == null || a == "") {
alert("Name must be filled out");
return false;
}
var b = document.forms["student_reg"]["email"].value;
if (b == null || b == "") {
alert("Email must be filled out");
return false;
}
var c = document.forms["student_reg"]["username"].value;
if (c == null || c == "") {
alert("Username must be filled out");
return false;
}
var d = document.forms["student_reg"]["password"].value;
if (d == null || d == "") {
alert("Password must be filled out");
return false;
}
var e = document.forms["student_reg"]["roll_no"].value;
if (e == null || e == "") {
alert("Roll no must be filled out");
return false;
}
}
html code is here
<body>
Login
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="" >
<span class="error"><p id="name_error"></p></span>
<p>EMAIL:</p>
<input type="text" name="email" value="" >
<span class="error"><p id="email_error"></p></span>
<p>USERNAME:</p>
<input type="text" name="username" value="" >
<span class="error"><p id="username_error"></p></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="" >
<span class="error"><p id="password_error"></p></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="" >
<span class="error"><p id="roll_no_error"></p></span>
<br/>
<br/>
<br/>
<input type="submit" name="submit" value="submit">
</form>
</body>
You can try this code:
It will check errors and returns at last after displaying all error messages if any.
function validateForm() {
var error = 0;
var a = document.forms["student_reg"]["name"].value;
document.getElementById('name_error').innerHTML = '';
if (a == null || a == "") {
// alert("Name must be filled out");
error++;
document.getElementById('name_error').innerHTML = 'Name must be filled out';
}
var b = document.forms["student_reg"]["email"].value;
document.getElementById('email_error').innerHTML = '';
if (b == null || b == "") {
// alert("Email must be filled out");
error++;
document.getElementById('email_error').innerHTML = 'Email must be filled out';
}
var c = document.forms["student_reg"]["username"].value;
document.getElementById('username_error').innerHTML = '';
if (c == null || c == "") {
// alert("Username must be filled out");
error++;
document.getElementById('username_error').innerHTML = 'Username must be filled out';
}
var d = document.forms["student_reg"]["password"].value;
document.getElementById('password_error').innerHTML = '';
if (d == null || d == "") {
// alert("Password must be filled out");
error++;
document.getElementById('password_error').innerHTML = 'Password must be filled out';
}
var e = document.forms["student_reg"]["roll_no"].value;
document.getElementById('roll_no_error').innerHTML = '';
if (e == null || e == "") {
// alert("Roll no must be filled out");
error++;
document.getElementById('roll_no_error').innerHTML = 'Roll no must be filled out';
}
if(error>0) {
return false;
}
return true;
}
Keep all the name attributes in array and validate in loop. As your ID is related to name attribute, concatenate the name with _error to get the ID of the error placeholder.
function validateForm() {
var names = ['name', 'email', 'username', 'password', 'roll_no'];
var errorCount = 0;
names.forEach(function(el) {
var val = document.forms["student_reg"][el].value;
if (val == null || val == "") {
document.getElementById(el + '_error').textContent = el.toUpperCase().replace('_', ' ') + " must be filled out";
++errorCount;
}
});
if (errorCount) return false;
}
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="">
<span class="error"><p id="name_error"></p></span>
<p>EMAIL:</p>
<input type="text" name="email" value="">
<span class="error"><p id="email_error"></p></span>
<p>USERNAME:</p>
<input type="text" name="username" value="">
<span class="error"><p id="username_error"></p></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="">
<span class="error"><p id="password_error"></p></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="">
<span class="error"><p id="roll_no_error"></p></span>
<br/>
<br/>
<br/>
<input type="submit" name="submit" value="submit">
</form>
You can iterate through all elements of the form student_reg to validate email and required and print error message under respective input field if no value was set:
const validateForm = () => {
const form = document.forms['student_reg'],
inputs = [...form.getElementsByTagName('input')],
errors = [...form.getElementsByClassName('error')],
regex = /\S+#\S+\.\S+/,
setErrorMsg = (str, msg) => `${str.replace('_', ' ')} ${msg}`
let countErrors = 0
inputs.forEach((input, index) => {
// clear all errors
(errors[index] || '').innerHTML = ''
// validate email
if (input.name === 'email' && !regex.test(input.value)) {
errors[index].innerText = setErrorMsg(input.name, 'should be valid')
countErrors++
}
// validate required
if (!input.value) {
errors[index].innerText = setErrorMsg(input.name, 'field is required')
countErrors++
}
})
return countErrors === 0
}
p {
font-size: 13px;
margin: 4px 0 0;
}
.error {
font-size: 12px;
padding: 6px 0 4px;
color: red;
display: block
}
.error:first-letter {
text-transform: uppercase
}
button {
margin-top: 8px;
font-size: 16px;
}
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="">
<span class="error"></span>
<p>EMAIL:</p>
<input type="text" name="email" value="">
<span class="error"></span>
<p>USERNAME:</p>
<input type="text" name="username" value="">
<span class="error"></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="">
<span class="error"></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="">
<span class="error"></span>
<button>Submit</button>
</form>
simple form It hold the Span for the Error msg.The span Id is very important here.you need to make color for errors using css
<form id="loginform" name="loginform" action="" method="post">
<label>Name</label>
<input type="text" name="username" />
<p></p>
<span id="usernameError"></span>
<p></p>
<label>Pwd</label>
<input type="password" name="password" />
<p></p>
<span id="passwordError"></span>
<p></p>
<input type="submit" value="Submit" />
</form>
script
<script type="application/javascript">
window.onload = function(){
function handleinput(){
if(document.loginform.username.value == ""){
document.getElementById("usernameError").innerHTML = "You must enter a username";
return false;
}
if(document.loginform.password.value == ""){
document.getElementById("passwordError").innerHTML = "You must enter a password";
return false;
}
}
document.getElementById("loginform").onsubmit = handleinput;
}
</script>

use flag to 'continue' in javascript?

I want to trigger submit_form function only after all fields are filled. Now the submit form will got triggered.
$('#submit').click(function() {
$('body input').each(function() {
if ($(this).val() == '') {
alert('Please fill in ' + $(this).attr('placeholder'));
$(this).focus();
return false;
}
})
submit_form();
});
function submit_form() {
alert('proceed to sumbit form.');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input type="" placeholder="name">
<br>
<br>
<input type="text" placeholder="hp">
<br>
<br>
<input type="text" placeholder="email">
<br>
<br>
<button id="submit">Submit</button>
</body>
ok, according to your code your submit functions always calls so i have added a flag for it please check....
$('#submit').click(function() {
var flag = 1;
$('body input').each(function() {
if ($(this).val() == '')
{
alert('Please fill in ' + $(this).attr('placeholder'));
$(this).focus();
flag = 0;
return false;
}
})
if(flag)
{
submit_form();
}
});
try this
$('#submit').click(function() {
var flag = 1;
$('body input').each(function() {
if ($(this).val() == '')
{
alert('Please fill in ' + $(this).attr('placeholder'));
$(this).focus();
flag = 0;
return false;
}
else
{
flag = 1;
}
})
if(flag)
{
submit_form();
}
});
function submit_form() {
alert('proceed to sumbit form.');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input type="" placeholder="name">
<br>
<br>
<input type="text" placeholder="hp">
<br>
<br>
<input type="text" placeholder="email">
<br>
<br>
<button id="submit">Submit</button>
</body>
Use a flag to prevent submitting your form when one input field is empty.
$('#submit').click(function() {
this.canSend = true;
$('body input').each(function() {
if ($(this).val() == '') {
this.canSend = false;
alert('Please fill in ' + $(this).attr('placeholder'));
$(this).focus();
return false;
}
})
if (this.canSend) {
submit_form();
}
});
function submit_form() {
alert('proceed to sumbit form.');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="" placeholder="name">
<br>
<br>
<input type="text" placeholder="hp">
<br>
<br>
<input type="text" placeholder="email">
<br>
<br>
<button id="submit">Submit</button>
A refactored version also available here:
https://jsfiddle.net/j74u8wvL/
Remove all JavaScript.
<body>
<input type="text" placeholder="name" required>
<br>
<br>
<input type="text" placeholder="hp" required>
<br>
<br>
<input type="email" placeholder="email" required>
<br>
<br>
<button id="submit">Submit</button>
</body>

how to validate single field in form when i have 5 fields using javascript?

I have a form which has four fields, when the all the fields are empty and submit button is clicked- it should alert "Please select at least one value".
When I enter the value in any of the fields the form should get submitted. I tried the following code but it's not working
function validatefleid() {
var computername = document.myform.computername.value;
var monitorname = document.myform.monitorname.value;
var tvname = document.myform.tvname.value;
var laptopname = document.myform.laptopname.value;
var cellphonename = document.myform.cellphonename.value;
if ((computername == null || computername == "") || (monitorname == null || monitorname == "") || (tvname == null || tvname == "") || (laptopname == null || laptopname == "") || (cellphonename == null || cellphonename == "")) {
alert("Please atleast one value");
return false;
}
}
<form name="myform" onsubmit="return validatefleid()">
computer
<input type="text" class="form-control inpt-bx-txtclr-home" name="computername" id="computerid" placeholder="000">monitor
<input type="text" class="form-control inpt-bx-txtclr-home" name="monitorname" id="monitorid" placeholder="000">tv
<input type="text" class="form-control inpt-bx-txtclr-home" name="tvname" id="tvid" placeholder="000">laptop
<input type="text" class="form-control inpt-bx-txtclr-home" name="laptopname" id="laptopid" placeholder="000">cellphone
<input type="text" class="form-control inpt-bx-txtclr-home" name="cellphonename" id="cellphoneid" placeholder="000">
<button type="submit">Calculate</button>
</form>
It is possible by iterating through all of the inputs within the form, and look for at least one input with value that's different than ''. Check the demo:
$(function(){
var $form = $('#myform');
$form.submit(function(){
var valid = false;
$('input', $form).each(function(){
if($(this).val() != ''){
valid = true;
}
});
if (!valid) {
alert("Please atleast one value");
}
return valid;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" name="myform">
computer<input type="text" class="form-control inpt-bx-txtclr-home" name="computername" id="computerid" placeholder="000">
monitor<input type="text" class="form-control inpt-bx-txtclr-home" name="monitorname" id="monitorid" placeholder="000">
tv<input type="text" class="form-control inpt-bx-txtclr-home" name="tvname" id="tvid" placeholder="000">
laptop<input type="text" class="form-control inpt-bx-txtclr-home" name="laptopname" id="laptopid" placeholder="000">
cellphone<input type="text" class="form-control inpt-bx-txtclr-home" name="cellphonename" id="cellphoneid" placeholder="000">
<button type="submit" >Calculate</button>
</form>
Without jQuery :
https://jsfiddle.net/uL28jsf9/
<script type="text/javascript">
function validatefleid()
{
var allFieldsNames = ['computername', 'monitorname', 'tvname', 'laptopname', 'cellphonename'];
var checkIfFieldEmpty function(fieldName) {
var fieldValue = document.myform[fieldName].value;
return fieldValue === "" || fieldValue === null
}
var allFieldsEmpty = allFieldsNames.every(checkIfFieldEmpty);
if (allFieldsEmpty) {
alert("Please atleast one value");
return false;
}
else {
alert("I'm ok with that !")
}
}
</script>
oops i have got the answer
I have a form which as four fields when the all the fields are empty and submit button is clicked it should alert as "please select atleast one value" when i entry the value in any of the one fields the form should get submitted i have tries the following code but its not working
<script type="text/javascript">
function validatefleid()
{
var computername=document.myform.computername.value;
var monitorname=document.myform.monitorname.value;
var tvname=document.myform.tvname.value;
var laptopname=document.myform.laptopname.value;
var cellphonename=document.myform.cellphonename.value;
if((computername==null || computername=="") && (monitorname==null || monitorname=="") && (tvname==null || tvname=="") && (laptopname==null || laptopname=="") && (cellphonename==null || cellphonename==""))
{
alert("Please atleast one value");
return false;
}
}
</script>
<form name="myform" onsubmit="return validatefleid()">
computer<input type="text" class="form-control inpt-bx-txtclr-home" name="computername" id="computerid" placeholder="000">
monitor<input type="text" class="form-control inpt-bx-txtclr-home" name="monitorname" id="monitorid" placeholder="000">
tv<input type="text" class="form-control inpt-bx-txtclr-home" name="tvname" id="tvid" placeholder="000">
laptop<input type="text" class="form-control inpt-bx-txtclr-home" name="laptopname" id="laptopid" placeholder="000">
cellphone<input type="text" class="form-control inpt-bx-txtclr-home" name="cellphonename" id="cellphoneid" placeholder="000">
<button type="submit" >Calculate</button>
</form>
here is a complete cross-browser working version of validatefleid function.
function validatefleid(){
var inputIds = ['computerid','monitorid','tvid','laptopid','cellphoneid'];
var hasEnteredAnyValue = false;
for(var i=0;i<inputIds.length;i++){
hasEnteredAnyValue = document.getElementById(inputIds[i]).value;
if(hasEnteredAnyValue)break;
}
if(!hasEnteredAnyValue)
{
alert("Please atleast one value");
return false;
}
}

Categories

Resources