9
I’m trying to register using Angularjs, but I want to get the validations that are in my model in Rails. But I’m having difficulties:
Covenat(model) Rails
validates :name, presence: true
controller Covenat Action Create
def create
@covenat = Covenat.new(covenat_params)
if @covenat.save
render json: @covenat, status: 200
else
render json: { errors: @covenat.errors }, status: 422
end
end
view /Assets/templates/covenats/new.html
<form name="form" ng-submit="submit()" novalidate>
<div class="form-group" ng-class="errorClass('name')">
<label class="control-label" for="covenat_name">Nome</label>
<input class='form-control' type='text' ng-model='covenat.name' name='covenat_name' id="covenat_name" required/>
<p class="help-block" ng-show="form.name.$invalid && form.name.$dirty">
{{ errorMessage('name')}}
</p>
</div>
</form>
covenats_new_controller.js
angular.module('clinica')
.controller('CovenatsNewCtrl', ['$scope', 'Covenat', '$location',
function($scope, Covenat, $location){
$scope.submit = function() {
console.log("submit")
function success(response) {
console.log("success", response)
$location.path("/covenats");
}
function failure(response) {
console.log("failure", response)
_.each(response.data, function(errors, key) {
_.each(errors, function(e) {
$scope.form[key].$dirty = true;
$scope.form[key].$setValidity(e, false);
});
});
}
Covenat.save($scope.covenat, success, failure);
};
$scope.errorClass = function(name) {
var s = $scope.form[name];
return s.$invalid && s.$dirty ? "error" : "";
};
$scope.errorMessage = function(name) {
var s = $scope.form[name].$error;
result = [];
_.each(s, function(key, value) {
result.push(value);
});
return result.join(", ");
};
}]);
I have the following error in Function Failure:
Typeerror: Cannot read Property '$invalid' of Undefined
on the line return s.$invalid && s.$dirty ? "error" : "";
There are 2 problems. 1. You are trying to load this:
$scope.form["name"]
and validate, try making aconsole.log($scope.form["name"])
thereof. 2. And there is no $invalid and $Dirty implementation on this object of your code that you published, that’s because it only arrow parameters in the commit failure... on the failure vc did not specify an error that must be checked.– Ivan Ferrer