Prevent validation of hidden fields in angularJS/ionic - javascript

I have this form and I have used ng-hide to hide some fields when meeting certain requirements. I have used validation for all the fields ( When a field is kept empty, it'll validate and ask to be fill the field). The problem is when my fields get hidden, still it seems to be validating. So I cannot proceed my form. How can I solve this problem?
I've used ng-required to the fields I've hidden and set it to false when that field is not needed, but it does not seem to work.
This is part of the form that I'm referring to:
<div class="form-group" ng-class="{ 'has-error' :submitted && (myForm.scheduler.$pristine || myForm.scheduler.$invalid)}">
<label class="labelColor"><h5><b>Payment Type *</b></h5></label>
<select type="select" class="textbox-n" id="scheduler" ng-model="data.scheduler" ng-change="scheduleChange()" ng-options="Scheduler.name for Scheduler in SchedulersArr" name="scheduler" required>
<option id="default" value="" selected="selected">--Select--</option></select>
<span class="help-inline" ng-show="submitted && (myForm.scheduler.$pristine || myForm.scheduler.$invalid)" >A Payment Type is required.</span>
</div>
<!-- Effective Date:-->
<div ng-hide = "hideFutureDate">
<div class="form-group" ng-class="{ 'has-error' : myForm.effectiveDate.$invalid && myForm.effectiveDate.$dirty && submitted || (myForm.effectiveDate.$invalid && myForm.effectiveDate.$pristine) && submitted }">
<label class="labelColor" ><h5><b>Effective Date*</b></h5></label><br>
<input style="width:100%" class="item-input-wrapper" type="date" id="effectiveDate" name="effectiveDate" ng-model="data.effectiveDate"
placeholder="Effective Date" ng-required="!hideFutureDate" />
<span class="help-inline" ng-show="submitted && myForm.startDate.$error.required" >A Effective date is required.</span>
<font color="red" >{{dateValidation}}</font>
</div>
</div>
<!--From/To Dates -->
<div ng-hide = "hideRecurrent" >
<div class="row" style="padding-left:15px">
<div class="form-group" ng-class="{ 'has-error' : myForm.startDate.$invalid && myForm.startDate.$dirty && submitted || (myForm.startDate.$invalid && myForm.startDate.$pristine) && submitted }">
<label class="labelColor" ><h5><b>From Date*</b></h5></label><br>
<input style="width:100%" class="item-input-wrapper" type="date" id="startDate" name="startDate" ng-model="data.startDate"
placeholder="From Date" ng-required="!hideRecurrent" />
<span class="help-inline" ng-show="submitted && myForm.startDate.$error.required" >A Start date is required.</span>
<font color="red" >{{dateValidation}}</font>
</div>
<div class="form-group" ng-class="{ 'has-error' : myForm.toDate.$invalid && myForm.toDate.$dirty && submitted || (myForm.toDate.$invalid && myForm.toDate.$pristine) && submitted }">
<label class="labelColor" ><h5><b>To Date*</b></h5></label><br>
<input style="width:100%" class="item-input-wrapper" type="date" id="toDate" name="toDate" ng-model="data.toDate"
placeholder="To Date" ng-required="!hideRecurrent" />
<span class="help-inline" ng-show="submitted && myForm.toDate.$error.required" >An End date is required.</span>
<font color="red" >{{dateValidation}}</font>
</div>
</div>
JS part
$scope.scheduleChange = function(){
if($scope.data.scheduler.name == 'Future Date'){
$scope.hideFutureDate = false;
$scope.hideRecurrent = true;
}
else if($scope.data.scheduler.name == 'Recurrent'){
$scope.hideFutureDate = true;
$scope.hideRecurrent = false;
}
I saw I can use ng-if to resolve this but not sure how.

You can indeed use ng-if to resolve this. Assuming your backend actually can handle blank inputs for things like data.startDate, then you can do:
<input ... ng-if="!hideRecurrent" />
Rather than show/hide the input, ng-if will actually remove it from the page when the condition is not met. And no input on the page means no validation error.

Related

validation msg not working properly after removing value in angular. what is the right way?

I am working on angular validation it was throwing validation on the page load itself which I don't want and also if I enter the value the validation msg disappears but if I go back into the textbox and delete the input it isn't throwing validation back. Please let me know what changes should I have to change to make it work
<div class="row">
<div class="input" style="margin-left:0px;">
First Name
<input type="text" [(ngModel)]="licenseInvite.FirstName" name="firstName" (ngModelChange)="update()" />
<span *ngIf="isInValidFirstName()" class="validation error">Please provide first name</span>
</div>
<div class="input" style="margin-left:0px;">
Last Name
<input type="text" [(ngModel)]="licenseInvite.LastName" name="lastName" (ngModelChange)="update()" />
<span *ngIf="isInValidLastName()" class="validation error">Please provide last name</span>
</div>
</div>
<div class="row">
<div class="input" style="margin-left:0px;">
Email Address
<input type="email" [(ngModel)]="licenseInvite.Email" name="email" (ngModelChange)="update()"
[attr.disabled]="editEmail==false ? 'disabled' : null" />
<span *ngIf="isInValid() && !isValidEmail()" class="validation error">Please provide a valid email address
</span>
</div>
public isValidEmail(): boolean
{
const regex = /^(([^<>()\[\]\\.,;:\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,}))$/;
const isValidEmail = regex.test(this.licenseInvite.Email);
// TODO: If member select...
return isValidEmail;
}
public isInValid():boolean {
const hasAllFields = this.licenseInvite.Email == null &&
this.licenseInvite.Role == null &&
this.licenseInvite.CountryCode == null;
return hasAllFields;
}
public isInValidFirstName(): boolean
{
return this.licenseInvite.FirstName == null
}
public isInValidLastName(): boolean
{
return this.licenseInvite.LastName == null
}
public isValid():boolean
{
return !this.isInValidFirstName && !this.isInValidLastName && !this.isInValid
}
public update(): void {
this.validLicenseInvite = this.isValid() ? this.licenseInvite : undefined;
}
you can use dirty and touched property e.g.
<span *ngIf="isInValid() && !isValidEmail() && (email.dirty || email.touched)" class="validation error">
for more info pls Refer to https://angular.io/guide/form-validation

Retrieving Data from Local Storage - key value pairs apparently don't match (error)

I am trying to make a functional login and registration pages (I know that in real life I need to store the login info in a database but for now I would like to see my pages "working"). I created two pages with forms one for registration and one for login. I also have two JS files one for locally storing input values (registerDetails.js) and one for retrieving those values during login (login.js).
Storing the information is not a problem, however, when I try to log in with the information I have just inputted and know it's correct it still throws an "Error" at me to say that password and username don't match even though I know they do match.
SOLUTION IN THE COMMENTS - MIX UP OF VARIABLES
I even tried to error handle if there is a problem with browser compatibility, still to no avail.
This is HTML for register.html:
<form class="form-horizontal">
<fieldset>
<div id="legend">
<legend>
Register or <a class="login-link" href="login.html">Login</a>
</legend>
<p>All fileds marked with * are required.</p>
</div>
<hr />
<div class="control-group">
<!-- Username -->
<label class="control-label" for="username"><span class="asterisk">*</span> Username</label>
<div class="controls">
<input type="text" id="username" name="username" placeholder="Any letters or numbers without spaces"
class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- E-mail -->
<label class="control-label" for="email"><span class="asterisk">*</span> E-mail</label>
<div class="controls">
<input type="text" id="email" name="email" placeholder="Enter your email here" class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- Password-->
<label class="control-label" for="password"><span class="asterisk">*</span> Password</label>
<div class="controls">
<input type="password" id="password" name="password" placeholder="Password of atleast 4 characters"
class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- Password -->
<label class="control-label" for="password_confirm"><span class="asterisk">*</span> Confirm Password</label>
<div class="controls">
<input type="password" id="password_confirm" name="password_confirm" placeholder="Please confirm password"
class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button type="submit" id="register" class="btn btn-success" onClick="store()">
Register
</button>
</div>
</div>
</fieldset>
</form>
Here is my HTML for login.html:
<form class="form-horizontal">
<fieldset>
<div id="legend">
<legend>
Login or <a class="login-link" href="register.html">Register</a>
</legend>
</div>
<hr />
<div class="control-group">
<!-- Username or Email-->
<label class="control-label" for="username">Username or Email</label>
<div class="controls">
<input type="text" id="usernameEmail" name="usernameEmail" placeholder="Enter your email or username"
class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- Password-->
<label class="control-label" for="password">Password</label>
<div class="controls">
<input type="password" id="passwordLogin" name="password" placeholder="Enter your password"
class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button class="btn btn-success" type="submit" onclick="check()">Login</button>
</div>
</div>
</fieldset>
</form>
My registration JS works fine, the browser prompts me to save credentials for later use...
Which is here:
// Getting details from the registration form to later store their values
var userName = document.getElementById('username');
var userEmail = document.getElementById('email');
var password = document.getElementById('password');
var passwordConfirm = document.getElementById('password_confirm');
// Locally storing input value from register-form
function store() {
if (typeof (Storage) !== "undefined") {
localStorage.setItem('name', userName.value);
localStorage.setItem('email', userEmail.value);
localStorage.setItem('password', password.value);
localStorage.setItem('password_confirmation', passwordConfirm.value);
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
}
My login page, however, throws the ERROR alert, even when I know for sure that the username and password match.
// check if stored data from register-form is equal to entered data in the login-form
function check() {
// stored data from the register-form
var storedName = localStorage.getItem('name');
// var storedEmail = localStorage.getItem('email');
var storedPassword = localStorage.getItem('password');
// entered data from the login-form
var userNameLogin = document.getElementById('usernameEmail');
var userPwLogin = document.getElementById('passwordLogin');
// check if stored data from register-form is equal to data from login form
if (userNameLogin.value == storedName && storedPassword.value == userPwLogin) {
alert('You are loged in.');
} else {
alert('ERROR.');
}
}
I have spent a few hours trying to rewrite the code to maybe see some typos or mistakes but I cannot find where I am going wrong! If anyone could help out as to show the reason why it does not match the username and password would be great.
It should alert me "You are logged in."
Thanks!
You have a typo
if (userNameLogin.value == storedName && storedPassword.value == userPwLogin) {
^^Here
}
Should be this instead
if (userNameLogin.value == storedName && userPwLogin.value == storedPassword ) {
}
By the way, your code will only log in with username (and not email) as it is. Don't forget to compare the email too.
Variables that are meant to store your elements at register page(userName, userEmail, etc.) might be null when store() is called.
I would suggest to get those inside the function:
function store() {
var userName = document.getElementById('username');
var userEmail = document.getElementById('email');
var password = document.getElementById('password');
var passwordConfirm = document.getElementById('password_confirm');
if (typeof (Storage) !== "undefined") {
localStorage.setItem('name', userName.value);
localStorage.setItem('email', userEmail.value);
localStorage.setItem('password', password.value);
localStorage.setItem('password_confirmation', passwordConfirm.value);
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
}
But the solution lies in this line:
if (userNameLogin.value == storedName && storedPassword.value == userPwLogin)
In your case storedPassword doesn't have "value" and userPwLogin does, since userPwLogin is the element on your form
Your code isn't working right because you've mixed up your local storage variable with your input elements. This line:
if (userNameLogin.value === storedName && storedPassword.value === userPwLogin) {
it should be:
if (userNameLogin.value === storedName && userPwLogin.value === storedPassword) {

In angular form span can not be displayed

I am not able to see error message on clicking the submit button using angularjs.
Any lead will be appreciated
Thanks in advance :)
<form id="formbody" ng-submit="submituser(form)" name="form" novalidate>
<input type="text" ng-class="{ errorinput: submitted && form.dob.$invalid }" name="dob" ng-model="dob" placeholder="Date of Birth" required />
<span class="e" ng-show="submitted && form.dob.$invalid">Please provide a valid date of birth</span>
<div style="padding-left: 275px;">
<button type="submit">Submit</button>
<!-- <div type="button" id="btn" style="color: red;" >Submit</div> -->
</div>
</div>
</form>
.controller('ExampleController', function($scope, $location, $scope, $stateParams) {
$scope.singleSelect = '';
$scope.goToPage = function() {
console.log("selectservice");
$location.path("/selectservice");
}
$scope.submituser = function($scope) {
if ($scope.form.$valid) {} else {
$scope.submitted = true;
}
}
})
change ng-show of span to
<span class="e" ng-show="submitted && form.dob.$invalid">Please provide a valid date of birth</span>
please check the form name
you have used two different names
name ="form" in form tag and used as signUpForm.dob in input field.
Check your ng-model to
<form id="formbody" ng-submit="submituser(form)" name="signUpForm" novalidate>
<input type="text" ng-class="{ errorinput: submitted && signUpForm.dob.$invalid }" name="dob" ng-model="form.dob" placeholder="Date of Birth" required />
<span class="e" ng-if="submitted && signUpForm.dob.$invalid">Please provide a valid date of birth</span>
<div style="padding-left: 275px;">
<button type="submit">Submit</button>
</div>
</div>
</form>
.controller('ExampleController',function($scope,$location,$scope, $stateParams){
$scope.singleSelect='';
$scope.goToPage=function(){
console.log("selectservice");
$location.path("/selectservice");
}
$scope.submitted =false;
$scope.submituser = function(form){
// console.log(form);
if (form.$valid) {
your logic
} else {
$scope.submitted = true;
}
}
})
Try something like that
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form" ng-app>
<div class="control-group" ng-class="{true: 'error'}[submitted && form.dob.$invalid]">
<label class="control-label" for="dob">Your Date of Birth</label>
<div class="controls">
<input type="text" name="dob" ng-model="dob" required />
<span class="help-inline" ng-show="submitted && form.dob.$invalid">Please provide a valid date of birth</span>
</div>
</div>
<button type="submit" class="btn btn-primary btn-large" ng-click="submitted=true">Submit</button>
</form>
You have to provide the form name but even after that you cannot refer to your form in controller unless you pass it through the submit function arguments. Also there is not signupForm() function in your controller.
The way to go is :
<form id="formbody" name="myForm" ng-submit="signupForm(myForm)" novalidate>
<!-- inputs etc -->
</form>
Then based on submituser():
$scope.signupForm = function(myForm) {
//Do whatever you want to do
if(myForm.$valid) {
//some logic
}else {
$scope.submitted = true;
}
}
On the other hand if you don't want to mess up with the controller you can always use FormController method $submitted. This would look like:
<span class="e" ng-show="myForm.$submitted && myForm.dob.$invalid">Please provide a valid date of birth</span>

How to use custom templates with Angucomplete-alt?

I'm working on a front-end application with ES6 and Angular. I'm trying to create a searchbox with autocomplete, and I want to use a custom template for the options list using Angucomplete-alt.
I created a template, but the options still have the standard format, and the execution doesn't throw errors. The examples page doesn't have a sample template.
Can someone give me an example of how to create the template?
My searchbox:
<angucomplete-alt id="country-search"
placeholder="Search countries"
pause="100"
selected-object="selectedCountry"
local-data="getCountries()"
search-fields="name"
title-field="name"
minlength="1"
template-url="/country-list-item.html"
input-class="form-control form-control-small"></angucomplete-alt>
The template:
<div class="autocomplete-template">
<div class="left-panel" style="display: inline-block;">
<span class="flag-icon flag-icon-{{ ::data.isoCode | lowercase}}"></span>
</div>
<div class="right-panel" style="display: inline-block;">
<span ng-bind-html="$highlight($getDisplayText())"></span>
</div>
</div>
All suggestions are welcome.
Thank you.
I have solved it. I copied the template's code from the html code of the examples page:
<div class="angucomplete-holder" ng-class="{'angucomplete-dropdown-visible': showDropdown}">
<p>This is custom</p>
<input ng-model="searchStr"
ng-disabled="disableInput"
type="text"
placeholder="{{placeholder}}"
ng-focus="onFocusHandler()"
class="{{inputClass}}"
ng-focus="resetHideResults()"
ng-blur="hideResults($event)"
autocapitalize="off"
autocorrect="off"
autocomplete="off"
ng-change="inputChangeHandler(searchStr)"/>
<div class="angucomplete-dropdown" ng-show="showDropdown">
<div class="angucomplete-searching" ng-show="searching" ng-bind="textSearching"></div>
<div class="angucomplete-searching" ng-show="!searching && (!results || results.length == 0)" ng-bind="textNoResults"></div>
<div class="angucomplete-row" ng-repeat="result in results" ng-click="selectResult(result)" ng-mouseenter="hoverRow($index)" ng-class="{'angucomplete-selected-row': $index == currentIndex}">
<div ng-if="imageField" class="angucomplete-image-holder">
<img ng-if="result.image && result.image != ''" ng-src="{{result.image}}" class="angucomplete-image"/>
<div ng-if="!result.image && result.image != ''" class="angucomplete-image-default"></div>
</div>
<div class="angucomplete-title" ng-if="matchClass" ng-bind-html="result.title"></div>
<div class="angucomplete-title" ng-if="!matchClass">{{ result.title }}</div>
<div ng-if="matchClass && result.description && result.description != ''" class="angucomplete-description" ng-bind-html="result.description"></div>
<div ng-if="!matchClass && result.description && result.description != ''" class="angucomplete-description">{{result.description}}</div>
</div>
<div class="angucomplete-row" ng-click="selectResult({title: searchStr, originalObject: { name: searchStr, custom: true }})" ng-mouseenter="hoverRow(results.length)" ng-class="{'angucomplete-selected-row': results.length == currentIndex}">
<div class="angucomplete-title">Select custom country '{{ searchStr }}'</div>
</div>
</div>
</div>

get input value after angularjs form validation

Hello everybody I'm quite new to Angularjs and Bootstrap. Now I have made login form using Angularjs and Bootstrap css.
The below is my form
<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>
<!-- USERNAME -->
<div class="form-group" ng-class="{ 'has-error' : userForm.username.$invalid && !userForm.username.$pristine }">
<label>Username</label>
<input type="text" id="name" name="username" class="form-control" ng-model="user.username" ng-minlength="3" ng-maxlength="8">
<p ng-show="userForm.username.$error.minlength" class="help-block">Username is too short.</p>
<p ng-show="userForm.username.$error.maxlength" class="help-block">Username is too long.</p>
</div>
<!-- EMAIL -->
<div class="form-group" ng-class="{ 'has-error' : userForm.email.$invalid && !userForm.email.$pristine }">
<label>Email</label>
<input type="email" id="email" name="email" class="form-control" ng-model="user.email">
<p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">Enter a valid email.</p>
</div>
<!-- PASSWORD -->
<div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$pristine }">
<label>Password</label>
<input type="password" id="pass" name="pass" class="form-control" ng-model="user.pass" ng-minlength="3" required>
<p ng-show="userForm.pass.$invalid && !userForm.pass.$pristine" class="help-block">Your pass is required.</p>
</div>
<button id="signIn_1" type="submit" class="btn btn-block signin">Submit</button>
</form>
and my app script is as
script>
// create angular app
var validationApp = angular.module('validationApp', []);
// create angular controller
validationApp.controller('mainController', function($scope) {
$scope.email = "fsdg#sdf.com";
$scope.password = "1234";
// function to submit the form after all validation has occurred
$scope.submitForm = function(isValid) {
// check to make sure the form is completely valid
if (isValid) {
};
});
</script>
Now my problem is how can i get above form input values after validation in angular app and send them to Codeigniter controller for authenticate.
Thanks in advance.
first declare
$scope.user={} in validation controller
In user object all value is available to you when user type because of ng-model
validationApp.controller('mainController', function($scope) {
$scope.email = "fsdg#sdf.com";
$scope.password = "1234";
$scope.user={};//Add this thing
// function to submit the form after all validation has occurred
$scope.submitForm = function(isValid) {
// check to make sure the form is completely valid
if (isValid) {
$http.post('index.php',$scope.user).success(function(response){
});
};
});
// At server end
// Remember one thing $http send data in json format.So decode it by json_decode

Categories