I seem to be stuck with a validation issue for 2 numbers which I am passing in the input field. I provide 2 numbers in the input, say num1 and num2. num2 must be greater than num1. If it is not, then I need to show an error message. This is what I have tried so far. I am not seeing the error message being shown consistently. Appreciate it if someone could point out what I might be missing.
JSFiddle
<input name="num1" type="text" ng-model="num1" placeholder="num1">
<input name="num2" type="text" ng-model="num2" placeholder="num2">
<span ng-show="num1>num2">Num2 cannot be lesser than num1</span>
Your Fiddle seems to work, except maybe that the message is showing also when num2 is empty. Changing type="text" to "type="number" makes it behave more like you would expect.
You have can use several ways
The first one is to change the input type to number
var app = angular.module("Demo", []);
app.controller("AppController", function($scope) {
});
<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>
<div ng-app="Demo">
<div ng-controller="AppController">
<div ng-form="regForm">
<input name="num1" type="number" ng-model="num1" placeholder="num1">
<input name="num2" type="number" ng-model="num2" placeholder="num2">
<span ng-show="num1>num2">Num2 cannot be lesser than num1</span>
</div>
</div>
</div>
Another is to use the input as text and associate a controller function to ng-show so that it compares the integer and not the string values
var app = angular.module("Demo", []);
app.controller("AppController", function($scope) {
$scope.checkNum = function(){
return parseInt($scope.num1) > parseInt($scope.num2)
}
});
<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>
<div ng-app="Demo">
<div ng-controller="AppController">
<div ng-form="regForm">
<input name="num1" type="text" ng-model="num1" placeholder="num1">
<input name="num2" type="text" ng-model="num2" placeholder="num2">
<span ng-show="checkNum()">Num2 cannot be lesser than num1</span>
</div>
</div>
</div>
Change the text box type="text" to type="number"
<input name="num1" type="number" ng-model="num1" placeholder="num1">
<input name="num2" type="number" ng-model="num2" placeholder="num2">
<span ng-show="num1 > num2">Num2 cannot be lesser than num1</span>
Demo
Related
Honestly thought this was an easy issue to solve, but I'm stuck trying to figure this out. I want to set my input-group spinner to show the value 1 when the user opens the application.
<input id="option1" type="number" min="1" value ="1"
class="form-control"
ng-model="targetEntity.option1">
</div>
I thought value="1" would solve the issue but it hasn't shown the desired result, I was wondering what am I doing wrong?
Initialize the value of targetEntity.option1 in your controller:
angular.module('app', [])
.controller('ctrl', ($scope) => {
$scope.targetEntity = {
option1: 1
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<input id="option1" type="number" min="1"
class="form-control"
ng-model="targetEntity.option1" />
</div>
I have two fields which both take numbers. One must always be higher than the other. For example you can have a field for age, and then a field for older sibling age which of course must be greater depending on the first field.
My fields are like this:
<input type="number" ng-model="age" required>
<input type="number" ng-model="olderSiblingAge" required>
I've tried using min="age" in the olderSibling input, but no luck, can still go below it.
You have to interpolate the value like this: min="{{vm.age}}" as specified in the number input documentation regarding to AngularJS.
angular
.module('app', [])
.controller('ctrl', function() {
var vm = this;
vm.age = 1;
vm.olderSiblingAge = 2;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl as vm">
<label> Age </label> <br />
<input type="number" ng-model="vm.age" required ng-change="vm.olderSiblingAge = vm.age">
<br /><br />
<label> Older sibling age </label> <br />
<input type="number" ng-model="vm.olderSiblingAge" required min="{{vm.age}}">
</div>
Note: I've used the controller-as syntax. Of course you can use it as your were doing it with the $scope notation like this min="{{age}}"
TRY USING THIS CODE
<input type="number" ng-model="age" required>
<input type="number" ng-change="olderSiblingAge = (olderSiblingAge < age)?age+1:olderSiblingAge" ng-model="olderSiblingAge" required>
To achieve expected result, use below option of using ng-blur to compare entered values
code sample https://codepen.io/nagasai/pen/XEJpYa?editors=1010
HTML:
<div ng-app="test" ng-controller="testCtrl">
Age <input type="number" ng-model="age" required>
Sibling Age <input type="number" ng-model="olderSiblingAge" required ng-blur="check()">{{olderSiblingAge}}
</div>
JS:
var app = angular.module('test',[]);
app.controller('testCtrl',function($scope){
$scope.check = function(){
if($scope.age > $scope.olderSiblingAge){
$scope.olderSiblingAge = null
alert("older sibling age should be greater than age")
}
}
})
I used to implement an Angular 2/4 application with Bootstrap 3 and used the Reactive Forms approach. I had a field-validation where the border of the input-field turned red and an error message appeared under the field in red font color.
it looks like this:
<div class="form-group row"
[ngClass]="{'has-error': (sourcesForm.get('sourceName').touched ||
sourcesForm.get('sourceName').dirty) &&
!sourcesForm.get('sourceName').valid }">
<label class="col-md-2 col-form-label"
for="sourceNameId">Source Name</label>
<div class="col-md-8">
<input class="form-control"
id="sourceNameId"
type="text"
placeholder="Source Name (required)"
formControlName="sourceName" />
<span class="help-block" *ngIf="(sourcesForm.get('sourceName').touched ||
sourcesForm.get('sourceName').dirty) &&
sourcesForm.get('sourceName').errors">
<span *ngIf="sourcesForm.get('sourceName').errors.required">
Please enter the Source Name.
</span>
<span *ngIf="sourcesForm.get('sourceName').errors.minlength">
The Source Name must be longer than 3 characters.
</span>
<span *ngIf="sourcesForm.get('sourceName').errors.maxlength">
The Source Name is too long.
</span>
</span>
</div>
</div>
Now i have to use Bootstrap 4 and neither the error message or the input-field turns red. How do i realise this? I tried to change the class of the parent span-block to "form-text" but it didn't work.
For beta version of Bootstrap v4, you can check out Form validation docs. There you can read about the new way, supported by all modern browsers for HTML5 way of form-validation with valid/invalid css classes. There Bootstrap uses the .was-validated and .invalid-feedback classes for what you want to achieve (see code snippet).
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"/>
<form class="container" id="needs-validation" novalidate>
<label for="validationCustom02">Last name</label>
<input type="text" class="form-control" id="validationCustom02" placeholder="Last name" value="Otto" required>
<label for="validationCustom03">City</label>
<input type="text" class="form-control" id="validationCustom03" placeholder="City" required>
<div class="invalid-feedback">
Please provide a valid city.
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
"use strict";
window.addEventListener("load", function() {
var form = document.getElementById("needs-validation");
form.addEventListener("submit", function(event) {
if (form.checkValidity() == false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add("was-validated");
}, false);
}, false);
}());
</script>
If you want something more similar to Bootstrap 3, you can use what they call server-side validation, as it is written:
As a fallback, .is-invalid and .is-valid classes may be used instead of the pseudo-classes for server side validation. They do not require a .was-validated parent class.
Previous answer for alpha version of Bootstrap V4 (if you must use this).
On Bootstrap V4 Form Validation Docs there is the following example:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="form-group has-danger">
<label class="form-control-label" for="inputDanger1">Input with danger</label>
<input type="text" class="form-control form-control-danger" id="inputDanger1">
<div class="form-control-feedback">Sorry, that username's taken. Try another?</div>
<small class="form-text text-muted">Example help text that remains unchanged.</small>
</div>
So i think you just need to change the has-error class to has-danger
This is the solution:
<div class="form-group row">
<label class="col-md-2 col-form-label"
for="sourceNameId">Source Name</label>
<div class="col-md-8">
<input class="form-control"
[ngClass]="{'is-invalid': (sourcesForm.get('sourceName').touched ||
sourcesForm.get('sourceName').dirty) &&
!sourcesForm.get('sourceName').valid }"
id="sourceNameId"
type="text"
placeholder="Source Name (required)"
formControlName="sourceName" >
<span class="invalid-feedback" *ngIf="(sourcesForm.get('sourceName').touched ||
sourcesForm.get('sourceName').dirty) &&
sourcesForm.get('sourceName').errors">
<span *ngIf="sourcesForm.get('sourceName').errors.required">
Please enter the Source Name.
</span>
<span *ngIf="sourcesForm.get('sourceName').errors.minlength">
The Source Name must be longer than 3 characters.
</span>
<span *ngIf="sourcesForm.get('sourceName').errors.maxlength">
The Source Name is too long.
</span>
</span>
</div>
</div>
i needed to put the [ngClass]into the input-tag. Then i had to define the class as is-invalid and set the parent span-class to invalid-feedback
i know that your question is for long time ago, but it is the best way to validate the form-control input field by reactive form technique and bootstrap 4 to display the validation. first you need to write some code for your form :
in html section:
<form [formGroup]="myForm">
<div class="form-group">
<label for="name">first Name: </label>
<input type="text" class="form-control" formControlName="firstName" id="name">
<div *ngIf="firstName.touched && firstName.invalid" class="alert alert-danger">
<div *ngIf="firstName.errors.required">filling name is required!</div>
</div>
</div>
in ts file, you should implement the logic to conduct the validation.
in ts file:
myForm = new FormGroup({
'firstName':new FormControl('',Validators.required)
})
//getter method
get firstName(){
this.myForm.get('firstName');
}
now you can see that the validation is working. now to give style to input field to show the red border around the invalid input, just go to css file of component and add this class to the css file:
.form-control.ng-touched.ng-invalid{border:2px solid red;}
and simply you can see the result.
I'm trying to create an angularjs form with two fields, one text input and a select. By default, the text input is blank but the select should have a value (the first element on the select). I'm following the angularjs form docs and using a master object which on reset is copied into the page's model. Here's the thing, if I set the select to something by default it comes blank. If I do the same with the text field it displays the default value. Below you'll find my code and here's a plunker. I think it might have to do with the copy being made on the reset function but I'm printing the object to the console at that point and it looks like it's being copied. If I try to do this without the master stuff, just setting it straight to the user and not calling reset it works ok.
controller
(function(angular) {
'use strict';
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.master = {};
$scope.businessUnits = [{"businessUnitId":1,"name":"Auto"},{"businessUnitId":2,"name":"Life"},{"businessUnitId":3,"name":"Health"},{"businessUnitId":4,"name":"Surety"},{"businessUnitId":5,"name":"Finance"},{"businessUnitId":6,"name":"Dwelling"}];
$scope.master.businessUnit = $scope.businessUnits[0];
$scope.master.name = "John";
$scope.update = function(user) {
$scope.master = angular.copy(user);
};
$scope.reset = function(form) {
if (form) {
form.$setPristine();
form.$setUntouched();
}
$scope.user = angular.copy($scope.master);
console.debug($scope.user.businessUnit);
};
$scope.reset();
}]);
})(window.angular);
html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example33-production</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="formExample">
<div ng-controller="ExampleController">
<form name="form" class="css-form" novalidate>
Name:
<input type="text" ng-model="user.name" name="uName" required="" />
<br />
<div ng-show="form.$submitted || form.uName.$touched">
<div ng-show="form.uName.$error.required">Tell us your name.</div>
</div>
E-mail:
<input type="email" ng-model="user.email" name="uEmail" required="" />
<br />
<div ng-show="form.$submitted || form.uEmail.$touched">
<span ng-show="form.uEmail.$error.required">Tell us your email.</span>
<span ng-show="form.uEmail.$error.email">This is not a valid email.</span>
</div>
<select class="form-control" ng-model="user.businessUnit" ng-options="unit as unit.name for unit in businessUnits" required></select>
Gender:
<input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female
<br />
<input type="checkbox" ng-model="user.agree" name="userAgree" required="" />
I agree:
<input ng-show="user.agree" type="text" ng-model="user.agreeSign" required="" />
<br />
<div ng-show="form.$submitted || form.userAgree.$touched">
<div ng-show="!user.agree || !user.agreeSign">Please agree and sign.</div>
</div>
<input type="button" ng-click="reset(form)" value="Reset" />
<input type="submit" ng-click="update(user)" value="Save" />
</form>
</div>
</body>
</html>
Add the following code to your <select>
ng-init="user.businessUnit = businessUnits[0]"
It should look like this:
<select class="form-control" ng-model="user.businessUnit" ng-init="user.businessUnit = businessUnits[0]" ng-options="unit as unit.name for unit in businessUnits" required></select>
I am making a program that requires the user to input a string into an HTML text input box but it has to be four characters. Is there any way to set a max value for the input? Also can you make it so it can only be numbers? Here is what I mean:
<html>
<head>
</head>
<body>
<h1>Please enter a four digit pin number:</h1>
<input type=text id=pin_number **maxvalue=4**>
/*Maybe you can do it with buttons*/
<table><tr><td><input type="button" value="1>"</td><td><input type="button" value="2>"</td>
<td><input type="button" value="3>"</td></tr><tr><td><input type="button" value="4>"</td><td><input type="button" value="5>"</td>
<td><input type="button" value="6>"</td></tr><tr><td><input type="button" value="7>"</td><td><input type="button" value="8>"</td>
<td><input type="button" value="9>"</td></tr></table>
</body>
</html>
<input type="number" max="9999" min="0" required value="0">
Fiddle.
Another solution, using the HTML5 pattern attribute:
<input type='text' pattern='\d\d\d\d' />
Fiddle
Again, I'm supposing you want exactly four digits. And you can type anything you want in, but an error is thrown when you click submit
Use Javascript and regular expressions like this:
<html>
<head>
<script language="javascript" type="text/javascript">
function pinnotify() {
var notify = document.getElementById('notify');
var numberRegex = new RegExp("^[0-9]+$");
var text = document.getElementById("pin");
if(numberRegex.test(text.value)){
notify.innerHTML = '<a style="font-size:1em;">Looks good!</a>';
}else{
notify.innerHTML = '<a style="font-size:1em;">Please numbers only.</a>';
}
if(text.value.length > 4){
text.value = text.value.substring(0,4);
}
}
</script>
</head>
<body>
<h1>Please enter a four digit pin number:</h1>
<form method="post" action="">
<input type="text" name="pin" id="pin" size="32" onkeyup="return pinnotify();"> <span id="notify"></span><br/>
</form>
</body>
</html>
Here is my way to filter digits and check max value in a text field.
It works in any browser
JS function:
function InputReplaceForInt(input, max) {
if(max > 0 && input.value.length > max) {
input.value = input.value.substr(0,max);
}
input.value = input.value.replace(/[^\d]/g, '');
}
Html code:
<input name="telephone" type="text" onkeyup="InputReplaceForInt(this,11)"/>