Validation in angularjs not working propoerly - javascript

<body ng-app="app" ng-controller="queryCtrl">
<form name="queryform" ng-submit="submitQuery(queryform.$valid)" novalidate="">
<legend>SEARCH</legend>
<div class="form-group" >
<label class="col-sm-2 control-label">Criteria 2:</label>
<input type="text" class="col-sm-4 form-control" name="input" ng-model="query.inputfield" required="" />
<p ng-show="queryform.input.$invalid && !queryform.input.$pristine" class="help-block">You name is required.</p>
</div>
<button type="submit" class="btn btn-primary" ng-disabled=!queryform.$valid>Submit</button>
</form>
Explain how i can resolve this issue.can any one explain proper validation procedure in angular .check out my plunker
Why ng-show is loading in the first place ?

validation works in this format
ng-show = "formname.inputname.$touched && formname.inputname.$invalid"
if the form is as below
<form name="formname">
<input name="inputname" ng-model="inputName" >
</form>
you can see all properties of an input by writing {{ formname.inputname | json }} in HTML , also if you want to see only error than can use {{ formname.inputname.$error | json }}
see the working plunker

Related

How to validate some fields and selects on ng-click AngularJS

I have a list of some input fields and few select options, so I want them be required on ng-click and raise a message just over the particular required item in form of PopupMenu or kind of that, or what ever the suitable way to show require warning just over the field
Hierarchy in my case:
<form>
<input required
<input required
location form for multiple records (not form tag)
contact form for multiple contacts (not form tag)
submit button to post (input required), all locations and all contacts.
</form>
My Form:
<div class="form-inline">
<div class="form-group">
<input type="text" placeholder="Legal Name" ng-model="companyForm.legalName" required/>
</div>
<div class="form-group">
<input type="text" placeholder="EIN" ng-model="companyForm.ein"/>
</div>
<div class="form-group" id="selectFormationDiv">
<select id="formationListId"></select>
</div>
<div class="form-group">
<input type="checkbox" style="margin-top: 5px;" ng-model="companyForm.internal"/> <b>Internal</b>
</div>
</div>
Note this is not form, and not be called on ng-submit.
My Output:
My Desired output:
Please guide me through how do I code to get my desired output. Thanks
angular.module('app', [])
.error {
color: red;
}
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<div ng-app='app'>
<form name="form" class="css-form" novalidate>
<input type='text' ng-model='temp1' required name='temp1' />
<span ng-show="form.temp1.$error.required && form.$submitted" class='error'>
field1 is required
</span>
<br>
<input type='text' ng-model='temp2' required name='temp2' />
<span ng-show="form.temp2.$error.required && form.$submitted" class='error'>
field2 is required
</span>
<br>
<input type="submit" value="Save" />
</form>
<hr>
<!--Solution without `<form>` tag: -->
<input type='text' ng-model='temp3' name='temp3' />
<span ng-show="!temp3 && $submitted" class='error'>field3 is required</span>
<br>
<input type='text' ng-model='temp4' name='temp4' />
<span ng-show="!temp4 && $submitted" class='error'>field4 is required</span>
<br>
<input type="button" ng-click='$submitted=true' value="Save" />
</div>

displaying error messages below the input form

I would like to know how can i display an error message below the input field using angular js. If the field is empty i want to display "This field is required". Also how to check if the field name starts with alphanumeric values like (\?/%*:|"<.>) i need to display the error "The field name should not start with alphanumeric values" below that input field. // code goes here
<div ng-controller="ModalController">
<form novalidate name="inputForm" class="form-horizontal">
<div class="row">
<div class="col-md-12">
<cp-input name="username" ng-model="user.name"
label="{{'formlabels.reponame' | translate}}" required="true"
error-state="right">
</cp-input>
</div>
</div>
<div style="color:red" ng-show="inputForm.username.$error.required">First name is required</div><br>
</form>
<!-- Show Confirm -->
<button type="button" class="btn btn-primary" data-dismiss="modal"
data-ng-click="submitData()">Add</button>
</div>
It would be a good idea to use ngMessages directive and ngPattern - take a look at the doc link with example
<form name="myForm">
<label>
Enter your name:
<input type="text"
name="myName"
ng-model="name"
ng-minlength="5"
ng-maxlength="20"
ng-pattern="^[^\w+$]"
required />
</label>
<pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre>
<div ng-messages="myForm.myName.$error" style="color:maroon" role="alert">
<div ng-message="required">You did not enter a field</div>
<div ng-message="minlength">Your field is too short</div>
<div ng-message="maxlength">Your field is too long</div>
</div>
</form>
ref https://docs.angularjs.org/api/ngMessages/directive/ngMessages
ng-messages will help you..Try this
<input ng-model="typeText" id="Sample" name="Sample" type="text" ng-pattern="^$|^[A-Za-z0-9]+" required/>
or ng-pattern="/^[a-zA-Z\s]*$/"
<div ng-messages="formname.Sample.$error">
<div ng-message="pattern">only characters are allowed</div>
<div ng-message="required">field required</div>
</div>

Angular JS textarea validation with required & showing error message

I have a Angular JS code where i want to implement validation and focus on the field back if textarea is empty.
<form ng-submit="addComment()" role="form" name="blogForm" novalidate>
<div class="form-group" ng-class="{ 'has-error' : blogForm.blogComment.$invalid && replySubmitted }">
<textarea ng-model="blogComment" name="blogComment" class="form-control" rows="3" ng-required="true" required></textarea>
</div>
<div style="color:#a94442;" ng-show="blogForm.blogComment.$invalid && replySubmitted">
<span ng-show="blogForm.blogComment.$error.required">Comment Text required.</span>
</div>
<button type="submit" ng-click="replySubmitted = true" class="btn btn-primary blog-bubmit-button">Submit</button>
</form>
For some reasons the above code is just inserting empty data and field is focused Invalid.
Any Suggestions may help me.
Thanku
you have define ng-app to process it as angular block.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app=''>
<form ng-submit="addComment()" role="form" name="blogForm" novalidate>
<div class="form-group" ng-class="{ 'has-error' : blogForm.blogComment.$invalid && replySubmitted }">
<textarea ng-model="blogComment" name="blogComment" class="form-control" rows="3" ng-required="true" required></textarea>
</div>
<div style="color:#a94442;" ng-show="blogForm.blogComment.$invalid && replySubmitted">
<span ng-show="blogForm.blogComment.$error.required">Comment Text required.</span>
</div>
<button type="submit" ng-click="replySubmitted = true" class="btn btn-primary blog-bubmit-button">Submit</button>
</form>
</div>

AngularJS Form validation Group error message

In angularJs FORM SUBMIT how to display all validation messagees in one single div at bottom of the page. Ex:
<div id="err-msg"> <!-- error message will come here --></div>
I referred documents but all are displaying below the text box using
<p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="alert alert-danger">Enter a valid email.</p>
How to write one area to bind all the messages in to same place (avoid use this userForm.email.$invalid)
Note I tried ng-message but am not clear any one help me. Please refer the below code for normal HMTL jQuery error display like need to take care using the AngularJS
HTML
<div id="main">
<form> <div><input id="email_txt" type="text" name ="email" value="" > </div>
<div><input id="pass_txt" type="password" name ="password" value="" > </div>
<div><input id="validate_btn" type="submit" value="Validate" > </div>
</form>
</div>
<div id="err-msg"> <!-- error message will come here --></div>
jQuery:
$('#main').on('click', '#validate_btn', function() {
if($('#email_txt').val().length == 0){
$('#err-msg').val("Please enter emailid!");
}else if($('#pass_txt').val().length == 0){
$('#err-msg').val("Please enter password!");
}
...
...
else{
alert("Good");
}
});
AngularJS current code :
<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>
<div class="form-group">
<label>Username</label>
<input type="text" 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>
<input type="email" name="email" class="form-control" ng-model="email">
<p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">Enter a valid email.</p>
<button type="submit" class="btn btn-primary">Submit</button>
<form>
app.js
.controller('validatectrl',['$scope',function($scope){
$scope.submitForm = function(isValid) {
// check to make sure the form is completely valid
if (isValid) {
alert('Good');
}
};
}]);
How to rewrite?
If a form is invalid, the errors will be stored in the object $scope.form.$error. Please check console of this JSFiddle. From the $error property on the form, you can populate the error messages.
angular.module('Joy', [])
.controller('FormCtrl', ['$scope', function ($scope) {
$scope.user = {};
$scope.submit = function () {
console.log($scope.userInfo);
};
}]);
The HTML:
<div ng-app="Joy" id="play-ground">
<form name="userInfo" novalidate ng-controller="FormCtrl">
<div class="ui input">
<input ng-model="user.email" ng-message="YOU ARE WRONG" name="User Email" type="email">
</div>
<div class="ui input">
<input ng-model="user.name" name="User Name" type="text" required>
</div>
<div class="ui divider"></div>
<button class="ui primary button" ng-click="submit()">Submit</button>
<div class="ui positive message">User: {{ user | json }}</div>
</form>
</div>

AngularJS does not proper handle button type="reset"?

I have the following:
<form name="editor">
<h2>Create/Update</h2>
{{ editor.title.$error.required }}
<div ng-class="{ 'has-error': editor.title.$invalid && editor.title.$dirty, 'has-success': editor.title.$valid }" class="form-group">
<input type="text" name="title" ng-model="project.title" placeholder="title" required class="form-control">
<span class="input-icon fui-check-inverted" ng-show="editor.title.$valid"></span>
</div>
{{ editor.description.$error.required }}
<div ng-class="{ 'has-error': editor.description.$invalid && editor.description.$dirty, 'has-success': editor.description.$valid }" class="form-group">
<textarea name="description" ng-model="project.description" placeholder="description" required class="form-control"></textarea>
<span class="input-icon fui-check-inverted" ng-show="editor.description.$valid"></span>
</div>
<button ng-click="save()" type="submit" class="btn btn-primary btn-embossed">Save</button>
<button type="reset" class="btn btn-inverse">Reset</button>
Back
</form>
I follow "JavaScript Projects" tutorial on angular website main page. I've added reset button to detail.html. The problem is it's behavior. When I cleaning fields by myself, the validation fails, but when I click on the reset button, fields are cleaning up but the form remaining valid.
Is that an angular bug? And how get it fixed?
I believe what you're looking for is $setPristine();
$setPristine();
Sets the form to its pristine state.
This method can be called to remove the 'ng-dirty' class and set the form to its pristine state (ng-pristine class). This method will also propagate to all the controls contained in this form.
Setting a form back to a pristine state is often useful when we want to 'reuse' a form after saving or resetting it.
via http://docs.angularjs.org/api/ng/type/form.FormController
Example JS
$scope.data = {
"username": "",
"password" : ""
};
$scope.reset = function() {
$scope.data.username = "";
$scope.data.password = "";
$scope.form.$setPristine();
};
Example Markup
<form name="form" id="form" novalidate>
<input name="username" ng-model="data.username" placeholder="Name" required/>
<input name="password" ng-model="data.password" placeholder="Password" type="password" required/>
<div>
<hr />
<button class="button" ng-click="">Login</button>
<button class="button" ng-click="reset()">Reset</button>
</div>
</form>
Demo http://plnkr.co/edit/xTQLQH8mCCkY0tIX6n8Y?p=preview
Update : simplified solution
If you wish to do away with the controller function reset(), you could set type="reset" as originally done, but still need to $setPristine() on ng-click
<button class="button" type="reset" ng-click="form.$setPristine()">Reset</button>
new plunk: http://plnkr.co/edit/tNKPyyMboAQjeURn6m6W?p=preview

Categories