I am very new to angularjs and I just cant figure out how I would go about validating my inputs.
I have an input which should never be empty. The model will always have a value. Whenever a user inputs invalid data (i.e nothing or maybe invalid characters) I would like the input to revert to its original value.
For instance, If the initial value was 50
and I deleted all of that (or entered text) and deselected the input, I would expect the input's value to change back to 50
.
Here is my controller:
var MyController = null;
app.controller("MyController", ["$scope", function($scope) {
$scope.data = myData;
$scope.validate = function(value, oldValue) {
if(!value || value == "") {
// Do something after validation
value = oldValue;
}
// Our value should be valid now (either replaced or changed)
}
MyController = $scope;
}]);
And my HTML (i would rather not have to type data.something
twice if possible):
<input type="text" ng-model="data.something" ng-change="validate()" />
Small Clarification: If the value of the input is "50" and a user removes the "0", the input would be at "5" which is valid. However if the user adds a "x" after I DONT want the input to change, it should still be at "5". However if all the input is empty, I would like onBlur
for the original value to be placed back into the input and the model unchanged.
<input type="text" ng-model="data.something" ng-change="validate()" required="required" />
– Baruch 14 hours agong-pattern
may also be helpful. – Jeroen 14 hours ago