Show ? in textbox when textbox have ng-pattern for numeric validation - angularjs

I need to show '?' when the value not able to read from scanner which returns me value by including '?'
Let say document has sr no as '123' but let say for some reason scanner not able to read it then it returns me as "12?" or "???" or "?23" or "1?3"
If any digit which is not readable that need to corrected by user manually for that i need to show them in to the textbox.
In our application we are using angularjs validations, which are not allowing me to show above values inside textbox as it contains '?' which is not numeric value.
Also I should enforce the numeric validation so that user can correct the above and submit to the server.
So how we achieve this functionality ?
<div ng-app ng-controller="formCtrl">
<form name="myForm" ng-submit="onSubmit()">
<input type="text" ng-model="price" name="price_field" ng-pattern="/^[0-9]{1,7}$/" required>
<span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span>
<input ng-show="toggle" type="submit" value="submit"/>
<input ng-show="!toggle" type="button" ng-click="AfterProcessing()" value="After Processing"/>
<input type="button" value="Reset" ng-click="reset()"/>
<br/>
<span>Activity : {{message}}</span>
</form>
</div>
JS code
function formCtrl($scope){
$scope.price= "123";
$scope.toggle = false;
$scope.message="No Activity";
$scope.onSubmit = function(){
$scope.toggle=false;
$scope.message="onSubmit clicked...";
}
$scope.AfterProcessing = function(){
$scope.toggle=true;
$scope.price ="1?3";
$scope.message="AfterProcessing clicked...";
}
$scope.reset=function()
{
$scope.toggle=false;
$scope.price ="123";
$scope.message="Reset clicked...";
}
}
I have created sample as below.
Plz check on JsFiddle sample
-Thanks

You need to create a CSS Class that will be applied to text box. Using :before and :after pseudo css construct, you can add ? character and get desired result.
So,
1. Define a CSS Class with :before and/or :after as per your requirement
2. On the HTML, use ng-class="{'your-class': $error, 'regular-class': '$pristine'}"
Let me know if you need a code sample and a plunker. (I am at the end of the day. May be will provide some code tomorrow. )
If you can create a plnkr based on above and submit link here, more people would be able to help you. thanks.

Related

Angular: Disable button on click after required fields are filled in the form

I need to disable the submit button after clicking on the button to prevent multiple submissions but before the it has to ensure that the required fields are filled.
I tried
<body ng-app="ngToggle">
<div ng-controller="AppCtrl">
<form name="newUserForm">
<input type="text" required>
<input type="text" required>
<input type="text">
<button ng-click="disableClick()" ng-disabled="isDisabled"
ng-model="isDisabled">Disable ng-click</button>
</form>
</div>
</body>
angular.module('ngToggle', [])
.controller('AppCtrl',['$scope', function($scope){
$scope.isDisabled = false;
$scope.disableClick = function() {
alert("Clicked!");
$scope.isDisabled = true;
return false;
}
}]);
but this will only disable the button without any validation
Ok, I get what you mean/want so I'll try to help and come up with some code - which is obviously missing but if it wasn't missing the necessary code, you'd have the solution :)
First, you'll have to properly write your form:
<form name="newUserForm" ng-submit="disableClick(newUserForm.$valid)" novalidate>
<input type="text" name="input1" ng-model="form.input1" required>
<input type="text" name="input2" ng-model="form.input2" required>
<input type="text" name="input3" ng-model="form.input3"> //not required
<button type="submit" ng-disabled="isDisabled">Disable ng-click</button>
</form>
so what we've got here, which you're missing:
You did name your form, but you're missing a submit, in the form as ng-submit or the button with type="submit", which will submit the form and that's when the validation happens
In order for Angular to validate your inputs, they need to have ng-model, otherwise it will not validate (HTML5 validation would, but read on)
I've added novalidate so we tell the browser "Hey, we need this validated but not by you, so do nothing", and Angular takes over
And last but not least, Angular adds a couple of properties to the form (see more here: Angular form Docs), $valid being one of them, which is set to true when all validated inputs are valid.
So this sums up the changes you needed to do to your form.
As for the Javascript part, there is just one small change:
$scope.disableClick = function(valid) {
if(valid && !$scope.isDisabled) {
$scope.isDisabled = true;
}
return false;
}
I guess the change is obvious, but I'll explain anyway - check that newUserForm.$valid (boolean) and if it's true (meaning form has passed validation) disable this button.
Of course, you'll have to add checks not to run the code on any type of submits and not just disabling the button (which can easily be re-enabled via Dev Tools), so that's why I added !$scope.isDisabled to the if statement.
Hope this answers your question :)
P.S. Here's a running demo in Plunker

Display validation messages when a button is clicked

I think what I want to achieve is quite simple. Let's have a form with a required field, a select for instance (I've also tried it with an input and it's exactly the same situation anyway).
I want to display the ng-messages only when a button is clicked. If the form field was touched before clicking the button, it works fine. But I cannot do it if the form field is $untouched.
I've solved it setting programatically $touched to the form field, but I'm wondering if there is any way to solve it without this uggly 'hack'.
// Any way to avoid this line??
$scope.myForm.favoriteColor.$setTouched();
//
Code for reference:
HTML:
<md-input-container>
<label>Favorite Color</label>
<md-select name="favoriteColor" ng-model="favoriteColor" required>
<md-option value="red">Red</md-option>
<md-option value="blue">Blue</md-option>
</md-select>
<div class="errors" ng-messages="myForm.favoriteColor.$error" ng-show="validateWithHack">
<div ng-message="required">Required</div>
</div>
</md-input-container>
JS:
$scope.validateWithHack = function() {
if ($scope.myForm.$valid) {
alert('Form is valid.');
} else {
// Any way to avoid this line??
$scope.myForm.favoriteColor.$setTouched();
//
$scope.validateWithHack = true;
}
};
I'm pretty sure that this was working with previous versions of angular-material. Now I'm using the latest 1.1.1.
Here is a plunker where the
problem can be easily reproduced.
Thanks in advance.
Check the CodePen
I have added novalidate to your form and added type="submit" to your md-button
Edit 2:
The type="submit" button actually triggers a form submit and so the angular form validates itself first, What we need to do is to prevent the submit and just do the validation.
novalidate(Just to supress the HTML5 validation) to your form and added type="submit" to your md-button : This Will Validate the form and submit the form, To validate and prevent form submit add ng-click="submitMethod(<yourForm>, $event)" to the <md-button> and define method as
$scope.submitMethod(form,ev){
ev.preventDefault();
//rest of your form work say if you want to do ajax or anything you like
//check if form valid using form.$invalid
}

Angular - Check if value entered into a field is a number

In my Angular app I have a field that accepts either an email address or a phone number.
If a number is entered I want to show a particular span. However I can't seem to get this working.
So in my controller I have written:
$scope.isNumber = function (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Then in my HTML I have:
<form name="registrationForm">
<div>
Email or Mobile
<span ng-show="isNumber(registrationForm.usernameReg)">Include the country code.</span>
</div>
<input name="usernameReg" ng-change="main.change()" type="text" ng-model="main.username">
</form>
Any ideas why this wouldn't work?
Thanks.
You need to be testing the value of the model.
try
ng-show="isNumber(main.username)"
registrationForm.usernameReg is an object that contains numerous properties used as part of validation.
To better see this add <pre>{{registrationForm |json}}</pre> in your view

Angular - Checking if a field is empty

Bit of a trivial one here however am new to Angular so excuse me.
Whenever I have an input field - I only want an action to occur if the field actually contains some valid content.
What i find I'm having to do is first instantiate a variable, then assign that to whatever input there is then do a boolean check in a if.
Is the the correct way to go around this? If i don't instantiate the variable (or don't use one at all) i run into getting undefined error:
var textToSearch = '';
textToSearch = $scope.main.searchInputField.trim();
if (textToSearch){
$location.path('/search/'+textToSearch);
}
Also (on another note)
I'm sanitising everything on the server side however on Angular/client side is there a quick and easy function I can use?
Thanks
I suppose you have an ng-model for 'main.searchInputField' so if you want to check if the field is empty you can just write
$scope.main = {};
if($scope.main.searchInputField.trim().length > 0){
//do stuff
}
suppose you have ng-model of input field 1 as some.data and input field 2 as some.data1
for(var i=0; i<$scope.some.length;i++){
if($scope.some[i]){
//do something
}
}
it will check every field.
This is using Bootstrap for email validation, but the same logic applies if you are using your own classes.
<div ng-class="(emailRegExp.test(email) && email != null) ? 'has-success' : 'has-error'" class="form-group has-feedback">
<div class="input-group">
<div class="input-group-addon">
<span class="glyphicon glyphicon-envelope"></span>
</div>
<input ng-model="email" ng-change="checkEnableSubmit()" id="email" placeholder="Email Address" type="text" class="form-control" aria-describedby="emailStatus">
</div>
<span ng-class="(emailRegExp.test(email) && email != null) ? 'glyphicon-ok' : 'glyphicon-remove'" class="glyphicon form-control-feedback" aria-hidden="true"></span>
</div>
The ng-class directive accomplishes the validation if:
The checkEnableSubmit() function in your controller only allows a submission when the data is valid (I would be happy to include that code, too)
Both classes in the ternary operator on line #1 indicate valid data and non-valid data (in this example one makes the input appear green and the other red)

Validating repeating inputs inside an AngularJS form

I know this has been asked before, and have even found a well-upvoted answer here:
How to validate inputs dynamically created using ng-repeat, ng-show (angular)
But I can't get that solution to work. I've got an example here - annoyingly both jsFiddle and Plunkr seem to be down right now.
Here's the JS:
app.controller('DetailsCtrl', ['$scope', function($scope) {
$scope.loading = false;
$scope.formData = {
lines: [{
text: 'test.com'}]
};
$scope.addRow = function() {
$scope.formData.lines.push({text:null});
};
}]);
Here's the markup:
<body ng-controller="DetailsCtrl">
<div>
<form name="mainForm" novalidate class="form-vertical">
...some non-repeating inputs go in here...
<div data-ng-repeat="line in formData.lines" data-ng-form="lineForm">
<input type="text" name="myinput" data-ng-model="line.text" data-ng-required="true">
<span data-ng-show="mainForm.lineForm.myinput.$error.required">Error!</span>
</div>
New Line
</form>
</div>
</body>
You'll notice initially there is one text input with text in - great. Click the 'New Line' link. Because the new text input fails validation - BOTH text inputs get the warning span shown... I just want the one span relating to the one empty text input to show up.
As AngularJS relays on input names to expose validation errors, and you used the same name for all inputs, you faced with this effect.
So you can't generate input name dynamically, but instead you can use ng-form (see https://docs.angularjs.org/api/ng/directive/ngForm).
<form name="mainForm" novalidate class="form-vertical">...some non-repeating inputs go in here...
<div data-ng-repeat="line in formData.lines" data-ng-form="lineForm">
<input type="text" name="myinput" data-ng-model="line.text" data-ng-required="true">
<span data-ng-show="lineForm.myinput.$error.required">Error!</span>
</div> New Line
</form>
EDIT. Please note, access to error myinput.$error.required instead of lineForm.myinput.$error.required.
Please, checkout working fiddle http://jsfiddle.net/Y9g4q/7/.

Resources