I have a input field like this :
<div class="form-group form-group-sm">
<label for="antispam" class="col-sm-2 control-label">1+1+5 = ?
<span class="myForm_error" ng-show="myFormZR.antispam.$error.required">(required field)</span>
<span ng-show="myFormZR.antispam.$dirty && IsMatch">BAD ANSWER</span></label>
<div class="col-sm-10">
<input type="text" class="form-control" name="antispam" placeholder="" required="required" ng-model="myForm.antispam" />
</div>
</div>
in ctrl :
/* antispam */
var antispamAnswer = "7"
if ($scope.myForm.antispam != antispamAnswer) {
$scope.IsMatch = true;
} else {
$scope.IsMatch = false;
}
It's not working, the mention "BAD ANSWER" is always show
Your code runs only once, when Controller is instantiated. You need put that code inside of $watch function for that ng-model:
$scope.$watch('myForm.antispam', function() {
// that code
})
Also do lots of console.log() to debug your code, so you know what and when is happening in your application.
Related
$(document).ready(function () {
jQuery.validator.addMethod("insz", function (value, element) {
var insz = $('#txtINSZ').val()
var controle = parseInt(insz.substring(13, 15))
var getal = insz.substring(0, 2) + insz.substring(3, 5) + insz.substring(6, 8) + insz.substring(9, 12)
var rest = parseInt(getal) % 97
alert("we doin' this mun")
return 97 - rest == controle;
}, "* Amount must be greater than zero");
$('#form1').validate({
rules: {
txtINSZ: {
required: $('#cbInsz').prop('checked') == false,
insz: function () {
$('#cbInsz').prop('checked') == true;
}
}
},
showErrors: function (errorMap, errorList) {
this.defaultShowErrors();// to display the default error placement
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.js"></script>
<form method="post" action="#" id="form1" a="" novalidate="novalidate">
<div id="container">
<div class="container-fluid">
<div class="col-xs-12">
<div class="form-horizontal col-xs-4" id="divDimLeft">
<span id="lblTitleAlgemeen">Algemen Informatie</span>
<div class="checkbox" style="margin-left:20px;">
<span id="lblCheck">
<input type="checkbox" id="cbInsz" checked="">
INSZ nummer werknemer gekend?
</span>
</div>
<div class="form-group" id="divINSZ">
<span id="lblINSZ" class="required" for="txtINSZ" aria-required="true">INSZ-nummer gekend?</span>
<input name="ctl00$ContentPlaceHolder1$txtINSZ" type="text" maxlength="15" id="txtINSZ" class="form-control required form valid" oninput="autoInvullen()" aria-required="true" placeholder="__.__.__-___.__" aria-invalid="false" required=""><label id="txtINSZ-error" class="error" for="txtINSZ" style="display: none;"></label>
</div>
<div class="form-group">
<span id="lblNaam" class="required" for="txtNaam" aria-required="true">Naam</span>
<input name="ctl00$ContentPlaceHolder1$txtNaam" type="text" maxlength="40" id="txtNaam" class="form-control form requiredField error" aria-required="true" aria-invalid="true"><label id="txtNaam-error" class="error" for="txtNaam">Dit veld is verplicht.</label>
</div>
<div id="divButton" class="text-right" style="width: 87.5%">
<input type="submit" name="ctl00$ContentPlaceHolder1$btnSubmit" value="Volgende" id="btnSubmit" class="btn btn-primary col-xs-2" style="float: none; min-width:200px;">
</div>
</div>
</div>
</div>
</div>
</form>
I wanted to make a custom validator but for some reason it's not working at all. The required does work so there is no issue with finding the elements in my page. So is there someone who has any idea why it is not working?
Thans in advance, under here you find the code i'm using including the method I wrote and the start of the validate method.
You can't just insert a comparison operator all by itself as the parameter; you need a function that returns the value of this parameter, in this case a boolean from the comparison operator...
$('#form1').validate({
rules: {
txtINSZ: {
required: function() {
return $('#cbInsz').prop('checked') == false;
},
insz: function() {
return $('#cbInsz').prop('checked') == false;
}
....
Solved it, I just putted the rules out of the rules section. After the validation code I putted this:
$('#txtINSZ').rules("add", {
required:true,
insz:true
})
Works perfectly.
I also faced the same situation, but in my case below two steps worked.
use data-rule-insz="true" attribute on your HTML input element for which you want custom validation.
also add a name attribute as mentioned in the below example:-
<input id="customer" name="customer" data-rule-insz="true" required type="text" class="typeahead form-control" />
I have a pretty big form that's being validated on the client side by Angular. I am trying to figure out how to reset the state of the form and its inputs just clicking on a Reset button.
I have tried $setPristine() on the form but it didn't really work, meaning that it doesn't clear the ng-* classes to reset the form to its original state with no validation performed.
Here's a short version of my form:
<form id="create" name="create" ng-submit="submitCreateForm()" class="form-horizontal" novalidate>
<div class="form-group">
<label for="name" class="col-md-3 control-label">Name</label>
<div class="col-md-9">
<input required type="text" ng-model="project.name" name="name" class="form-control">
<div ng-show="create.$submitted || create.name.$touched">
<span class="help-block" ng-show="create.name.$error.required">Name is required</span>
</div>
</div>
</div>
<div class="form-group">
<label for="lastName" class="col-md-3 control-label">Last name</label>
<div class="col-md-9">
<input required type="text" ng-model="project.lastName" name="lastName" class="form-control">
<div ng-show="create.$submitted || create.lastName.$touched">
<span class="help-block" ng-show="create.lastName.$error.required">Last name is required</span>
</div>
</div>
</div>
<button type="button" class="btn btn-default" ng-click="resetProject()">Reset</button>
</form>
And my reset function:
$scope.resetProject = function() {
$scope.project = {
state: "finished",
topic: "Home automation"
};
$("#create input[type='email']").val('');
$("#create input[type='date']").val('');
$scope.selectedState = $scope.project.state;
// $scope.create.$setPristine(); // doesn't work
}
Also if you could help me clear the input values of the email and date fields without using jQuery would be great. Because setting the $scope.project to what's defined above doesn't reset the fields for some reason.
Try to clear via ng-model
$scope.resetProject = function() {
$scope.project = {
state: "finished",
topic: "Home automation"
};
$("#create input[type='email']").val('');
$("#create input[type='date']").val('');
$scope.selectedState = $scope.project.state;
$scope.project = {
name: "",
lastName: ""
};
}
As mentioned in the comments, you can use $setUntouched();
https://docs.angularjs.org/api/ng/type/form.FormController#$setUntouched
This should set the form back to it's new state.
So in this case $scope.create.$setUntouched(); should do the trick
Ref all that jquery. You should never interact with the DOM via controllers. That's what the directives are for
If you want to reset a given property then do something like:
$scope.resetProject = function() {
$scope.project = {
state: "finished",
topic: "Home automation"
};
$scope.project.lastName = '';
$scope.project.date= '';
}
I am using AngularJS ng-change directive, I want to clear the data in the form for some fields when ng-change invoke , how i can achieve this task using this approach.
So far i have tried below code...
HTML
<div class="form-group col-md-6" ng-show="showEditdisForm">
<div>
<label class="control-label" for="controlEffBusiness">Overall
Control Effectiveness Business</label>
</div>
<div>
<select kendo-drop-down-list k-data-value-field="'id'"
k-data-text-field="'text'" k-option-label="'Select'"
k-data-source="ctrlEffOptions"
ng-model-options="{ updateOn: 'blur' }"
ng-model="processRating.controlEffectivenessRatingOverrideKey" ng-change="overrideBusinessDec(processRating.controlEffectivenessRatingComputeKey)"></select>
</div>
</div>
</div>
<div class="row" ng-show="OverrideComments" ng-class="{'has-error': processRatingForm.OverallBusComment.$dirty && processRatingForm.OverallBusComment.$invalid, 'has-success': processRatingForm.OverallBusComment.$valid}">
<div class="form-group col-md-6">
<label class="control-label" for="controlEffBusiness">
Overall Control Effectiveness Business Comments</label>
</div>
<div class="col-md-10">
<textarea rows="2" class="form-control"
ng-pattern="/^[a-zA-Z0-9_ ]*$/"
required
id="OverallBusComment"
name="OverallBusComment"
ng-model-options="{ updateOn: 'blur' }"
data-required-msg="Overall Control Busniess comment is required"
ng-model="processRating.overallControlEffectivenessOverrideText"></textarea>
</div>
</div>
CTRL.JS
$scope.resetData = function (){
$scope.processRating.overallControlEffectivenessOverrideText = '';
$scope.processRating.residualRiskRatingOverrideKey ='';
$scope.processRating.residualRatingText = '';
}
$scope.overrideBusinessDec = function() {
$scope.OverrideComments = true;
if (!($scope.processRating.controlEffectivenessRatingOverrideKey == $scope.processRating)) {
Rating.getProcessRatingFields($scope.processRating.inherentRiskRatingKey,$scope.processRating.controlEffectivenessRatingComputeKey).then(function (response){
$scope.processRatingFields = response.data;
$scope.resetData();
})
} else {
$scope.OverrideComments = false;
}
};
Since you're inside a promise result, you need to call $scope.$apply to make your changes effective.
Rating.getProcessRatingFields($scope.processRating.inherentRiskRatingKey, $scope.processRating.controlEffectivenessRatingComputeKey).then(function (response) {
$scope.$apply(function() {
$scope.processRatingFields = response.data;
$scope.resetData();
});
});
Hey so I have a form which has three fields name,email and phone.
<div ng-show="Nerd.adding">
<form class="col-sm-6" name="Nerd.nerdAddFrm" novalidate >
<div class="form-group">
<label for="inputName">Name</label>
<input type="text" class="form-control" id="inputName" placeholder="Name" ng-model="Nerd.nerd.name" required >
</div>
<div class="form-group">
<label for="inputEmail">Email</label>
<input type="email" class="form-control" id="inputEmail" placeholder="Email" ng-model="Nerd.nerd.email" required >
</div>
<div class="form-group">
<label for="inputPhone">Phone</label>
<input type="text" class="form-control" id="inputPhone" placeholder="Phone" ng-model="Nerd.nerd.phone" required >
</div>
<button ng-click="Nerd.saveNerd(Nerd.nerd)" type="submit" class="btn btn-primary">Submit</button>
<button ng-click="Nerd.load()" type="button" class="btn btn-default">Cancel</button>
</form>
</div>
As you can see the cancel button calls a Nerd.load() function in the controller. The controller basically resets the view and resets all the binded data to the model.
Nerd.load = function () {
Nerd.editing = false;
Nerd.adding = false;
Nerd.nerd = [];
nerdResource.query(
function (data) {
Nerd.nerds = data;
}
);
};
You can see that I am setting Nerd.nerd equal to an empty array. This should empty out the form fields data. It works fine for Name and Phone. But when I go back to the page it still shows what was last typed. There is no page reload as I am showing and hiding divs based on controller variables. EG <div ng-show="Nerd.adding">. Can anyone help me out with this?
I am on angularjs version 1.3.14. Any help on this would be great.
Thanks.
You need to attach these variables to your $scope like so:
$scope.Nerd.load = function () {
$scope.Nerd.editing = false;
$scope.Nerd.adding = false;
$scope.Nerd.nerd = [];
nerdResource.query(
function (data) {
$scope.Nerd.nerds = data;
}
);
};
Also, I think you should set $scope.Nerd to an empty object like:
$scope.Nerd = {};
instead of setting it to an empty array. You need to use $scope when interacting with the view. This code doesn't look the angular the way it is currently written.
If you can try according some way.
Nerd.load = function () {
Nerd.editing = false;
Nerd.adding = false;
Nerd.nerd = [];
nerdResource.query(
function (data) {
Nerd.nerds = data;
Nerd.nerd = []; // Put here and array make Empty
}
);
};
I am populating values in dropdown in below html code , if user change dropdown i want to use ng-show and display text area so user can enter comments , How i can achieve that using AngualrJS directive ng-change.
So far tired this...
HTML
<form kendo-validator="ratingValidator" name="processRatingForm"
novalidate ng-cloak ng-controller="EditProcessRatingCtrl"
class="border-box-sizing grids-fonts">
<p class="status">{{PrcsratingValidationMsg}}</p>
<div class="row">
<div class="form-group col-md-6" ng-show="showEditdisForm">
<div>
<label class="control-label" for="controlEffBusiness">Overall
Control Effectiveness Business</label>
</div>
<div>
<select kendo-drop-down-list k-data-value-field="'id'"
k-data-text-field="'text'" k-option-label="'Select'"
k-data-source="ctrlEffOptions"
ng-model-options="{ updateOn: 'blur' }"
ng-model="processRating.controlEffectivenessRatingOverrideKey" ng-change="overrideBusinessDec()"></select>
</div>
</div>
</div>
<div class="row" ng-show="OverrideComments">
<div class="form-group col-md-6">
<label class="control-label" for="controlEffBusiness">
Overall Control Effectiveness Business Comments</label>
</div>
<div class="col-md-10" kendo-validator="overrideCommentValidator">
<textarea rows="2" class="form-control" required
data-required-msg="Business override justification is required"
ng-model="processRating.overallControlEffectivenessOverrideText"></textarea>
</div>
</div>
CTRL.JS
$scope.riskDirOptions = kendoCustomDataSource.getDropDownDataSource("RSDL_RSK_DIR");
$scope.riskBusinessOptions = kendoCustomDataSource.getDropDownDataSource("RSDL_RR");
$scope.ctrlEffOptions = kendoCustomDataSource.getDropDownDataSource("CTL_EFCTVNS_RT");
$scope.disableEffComp = true;
$scope.compReadOnly = true;
//Edit Function broadcast from parent Ctrl
$scope.$on('editProcessRating', function() {
$scope.showEditdisForm = true;
$scope.ProcessRatingWin.open().center();
if($scope.processRating.inherentRiskRatingKey === null || $scope.processRating.finalOutcomeInherentRiskRatingKey === null
|| $scope.processRating.controlEffectivenessRatingComputeKey === null) {
$scope.showEditdisForm = false;
$scope.PrcsratingValidationMsg = '*All Computed values are required*';
} else {
return true;
}
});
//Edit Save Functionality
$scope.saveProcessRating = function() {
Rating.saveProcessRating($scope.processRating).then(function(){
$rootScope.$broadcast("refreshRatingGrid");
$scope.ProcessRatingWin.close();
});
}
$scope.overrideBusinessDec = function() {
if (!($scope.processRating.controlEffectivenessRatingOverrideKey !==null)) {
$scope.OverrideComments = true;
} else {
$scope.OverrideComments = false;
}
};
$scope.closeModal = function() {
$scope.ProcessRatingWin.close();
};
Not exactly sure what you want. But this is a simple implementation of ng-change
Here is the HTML
<select data-ng-model="valueSelected"
ng-options="opt as opt.label for opt in options" ng-change="handleChange()">
</select>
Here is the .js file
app.controller('settingsCtrl',function($scope) {
$scope.handleChange = function(){
console.log(valueSelected);
}
});
The scope.handleChange will be executed every time there is a change in the dropdown.
and In your HTML try using 'ng-if' in place of 'ng-show'.
I am not sure if the scope variables you declared in the ng-change function are updated try to use a watch if needed.
Hope this will also help for your reference getting the ng-object selected with ng-change
hope it helps ! :)