Required field validation on submit in angular js - javascript

I have a requirement of displaying two required fields on page. I have a datePattern and required field check.
I need to display field is required on submit without entering fields . If I enter something my datePattern works fine. Since it is required when I display like
Ng-show = Form.field1.$error.required && Form.field1.$pristine. This displays required message on start but I want this on submit and once I edit my field datePattern comes into picture this is fine.
I have tried ng-click=submitted = true. And ng-submit=ctrl.submit() it's not entering into controller..
Can some one help...

I fixed this way
Form.$submitted && form.field1.$error.required && !form.field1.$touched

<form ng-submit="validateForm()">
<input ng-model="name">
<span ng-show="invalidName">Please fill name field</span>
</form>
controller('MyController', function ($scope){
$scope.validateForm = function(){
if($scope.name){
$scope.invalidName = true;
}
if($scope.invalidName){
//Prevent submit
return false;
}else{
//Handle submit here or do nothing for auto submit of form
}
};
});

The way I handle this (no promises that it is the best way) is that on the submit function I set each form field to $touched, then for each field I show the warning when the field is $error and $touched.
jsfiddle
HTML
<div ng-app="app" ng-controller="ctrl">
<div ng-form="forms.datesForm">
<input type="text" ng-model="date" name=date required />
<p ng-show="forms.datesForm.date.$touched && forms.datesForm.date.$invalid">Please select a date.</p>
<br />
Your date: {{date}}
<button ng-click="submitForm()">Submit</button>
</div>
<p ng-show="submitted">
Congrats, you submitted successfully!
</p>
</div>
JS
angular.module('app', []);
angular.module('app').controller('ctrl', ['$scope', function ($scope) {
$scope.forms = {};
$scope.submitForm = function() {
if ($scope.forms.datesForm.$invalid) {
setAllFieldsTouched($scope.forms.datesForm);
return;
}
else {
// do whatever submit logic here
$scope.submitted = true;
}
}
var setAllFieldsTouched = function () {
// loop through all the empty required fields
angular.forEach($scope.forms.datesForm.$error.required, function (field) {
// only forms have $submitted properties, not fields
if (field.hasOwnProperty('$submitted')) { // is a form, recur through it
setAllFieldsTouched(field);
}
else { // this is a field
field.$setTouched();
}
});
}
}]);

Related

select either file or textarea data with ng-click

I want to select either file or entered data. i need to validate that but i failed. it takes must be either file or text data only with button click. please help me to solve this problem thanks in advance. JSFiddle
i need if user entered both file and textarea text it shows error. user must select either file or textarea only. this is my requirement
HTML:
<form name="form" ng-app="app" ng-controller="Ctrl" >
Upload file: <input type="file" id="file" /><br/><br/>
Enter text: <textarea id="textarea" required></textarea>
<br/><br/>
<button type="submit" class="btn btn-primary btn-large" ng-click="submitForm()">Submit</button>
</form>
JS:
var app = angular.module('app', []);
app.controller('Ctrl', function ($scope) {
$scope.submitForm = function(){
alert("hi");
var string1 = document.getElementById('file').value;
var string2 =document.getElementById('textarea').value;
if (string1 == string2) {
return true;
}
else {
return false;
}
}
});
There's no how to get the filename with ng-model for it doesn't work with type=file.
To achieve what you want, you must create a directive, as seen in the link below:
https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs
After that, you must assign the file-model directive to the input, telling which variable of the $scope will be two-way-binded with the value.
The textarea data could be achieved with ng-model.
JSFiddle
once you click on file input then disable the textarea field and if u don't have any file to upload you can click on text area field and onClick of textarea disable file input
You can't use required on both inputs if it's an either or condition.
I created a codepen that should work for you here:
http://codepen.io/anon/pen/XdYBWp
Here's the code:
HTML
<form name="form" ng-app="app" ng-controller="Ctrl as ctrl">
Upload file:
<input type="file" id="file" ng-model="ctrl.file" />
<br/>
<br/> Enter text:
<textarea id="textarea" ng-model="ctrl.text"></textarea>
<br/>
<br/>
<button class="btn btn-primary btn-large" ng-click="ctrl.submitForm()">Submit</button>
</form>
JavaScript
angular.module('app', []).controller('Ctrl', function() {
var vm = this;
vm.file = ""
vm.text = ""
vm.submitForm = function() {
// angular doesn't update the model for input type="file"
vm.file = document.getElementById('file').value;
var retVal = false ;
if (vm.file && ! vm.text)
{retVal = true}
else if (vm.text && ! vm.file)
{retVal = true}
else if (!vm.text && !vm.file)
{retVal = false}
else if (vm.text && vm.file)
{retVal = false}
if (!retVal) {
alert("Please specify either a file or text, not both!")
} else
alert("ok")
}
});
You probably could combine all the ifs & else ifs into a single expression, but it wouldn't be very readable IMO.

apply angular validations only after submit and not to show validations, if user removed text from text box after submit

Apply angular validations only after submit and not to show validations, if user removed text from text box after submit.
my requirement is technically,
--> if user entered text it should not show any validation
--> show validations only after if user clicked on submit
&
--> after submit if user touched that text box (or) removed text from text box then validation msgs should not show
can you guys please give me solution,
fast replies are appreciated, If you provide me fiddles then i would be very thankful.
thanks in advance
You can solve the problem by using a flag. Assume you have a form that contains an input. You have to set the flag isSubmitted to true when you clicked the submit button. and make it false when your input changes. Then show your validation message based on that flag:
Here is a hypothetical controller:
function appCtrl($scope) {
$scope.isSubmitted = false;
$scope.submit = function() {
$scope.isSubmitted = true;
//...
}
$scope.inputChanged = function() {
$scope.isSubmitted = false;
}
}
And this can be a part of your view:
<input name="inputName" type="text" ng-model="myModel" ng-change="inputChanged()" required="" />
<span ng-show="form.$error.required && form.$dirty && isSubmitted">name is required</span>
I don't know exactly what you are looking for, but I guess this piece of code could be useful.
It's just a basic form with its controller and some validated field.
Each field is required in this example, but as you can see no validation feedback is given to the user.
The validation pass only if the form is valid and then the submission is registered with a flag ( true/false ).
If the flag is true and the user touch one of the fields, all fields are blank again.
The Controller
(function(){
var Controller = function($scope){
// Parameters
var isFormSubmitted = false;
// Methods
// Shared Methods
$scope.checkFocus = function(){
if(!isFormSubmitted){
return;
}
// Reset all fields
$scope.fields = null;
// Do something
}
$scope.validate = function(){
isFormSubmitted = true;
// Do some validation
};
};
Controller.$inject = [
'$scope'
];
app.controller('MainCtrl', Controller);
})();
The view
<div ng-controller="MainCtrl">
<form name="form" ng-submit="form.$valid && validate()" novalidate>
<input ng-focus="checkFocus()" ng-model="fields.username" type="text" required placeholder="Username">
<input ng-focus="checkFocus()" ng-model="fields.password" type="password" required placeholder="Password">
<input type="submit" value="Submit">
</form>
</div>

Enable a button based on an input value

I have an observable that contains two values. I want to enable a button if the input value is not empty. I check if the value is not empty with a function. Please help, here is a jsfiddle example of what I'm trying to achieve: http://jsfiddle.net/zNLNy/1213/.
Here is some code:
<div id="form">
<input type="text" data-bind="value: message" />
<button data-bind="enabled: canSend">Send</button>
</div>
var chatFormObservable = kendo.Observable({
message: "",
canSend: function(){
return this.get("message") != ""
}
});
kendo.bind($("#form"), chatFormObservable);
The function you need is "subscribe"; you need to subscribe to the input value and enable the button if a value is entered, else disable it:
self.message.subscribe(function (value) {
if(value){
self.canSend(true);
}
else{
self.canSend(false);
}
});

make a field mandatory using javascript

I am trying to make a select field mandatory on a web page. I know how to do it with help of JS and form attribute 'onsubmit' and returning the function. But the problem is that form code is already written and I dont know how to add attribute now. Let me know if I can append attribute dynamically from JS.
The other way I tried is to call the JS after page loaded. But this isnt making the field mandatory and form can be submitted.
Following is my code..
<!DOCTYPE html>
<html>
<head>
<script>
function f1()
{
var countryValue = document.getElementById('count ID').value;
if (countryValue == "")
{
alert("field value missing");
return false;
}
var stateValue = document.getElementById('state ID').value;
if (stateValue == "")
{
alert("state field value missing");
return false;
}
}
</script>
</head>
<body>
<form method = "post" action = "33.html">
Country: <input type="text" id="count ID">
state: <select id="state ID">
<option></option>
<option value="ap">ap</option>
<option value="bp">bp</option>
</select>
<br>
<input type = "submit">
</form>
<script>window.onload=f1</script>
</body>
</html>
Please help.
Have a look at this since you have messed up the IDs
Live Demo
window.onload=function() {
document.forms[0].onsubmit=function() { // first form on page
var countryValue = this.elements[0].value; // first field in form
if (countryValue == "") {
alert("Please enter a country");
return false;
}
var stateIdx = this.elements[1].selectedIndex; // second field
if (stateIdx < 1) { // your first option does not have a value
alert("Please select a state");
return false;
}
return true; // allow submission
}
}
PS: It is likely that POSTing to an html page will give you an error
To get the last button to do the submission
window.onload=function() {
var form = document.forms[0]; // first form
// last element in form:
form.elements[form.elements.length-1].onclick=function() {
...
...
...
this.form.submit(); // instead of return true
}
}
Once you've got a function to detect improper values (empty mandatory field or anything else, like a bad e-mail address for instance) you have a few different options :
disable the submit button
cancel the onclick event on the button
cancel the submit event on the form
disabling the submit button can be annoying for the user (it might flash on and off while the values are entered).
I had the same issue, but i made a extension. Using hook system to translate fields with "*", in the names, to validate like required field. This is a simple solution not intrusive where is not required addition of fields in the database, only by the use of sufix "*" in configuration of custom fields.
There is the code: https://github.com/voiski/bugzilla-required-field

Preventing Text Submission In Controller Failing

I'm running a simple example from the main page of Angular involving a todo list. I want to prevent the user from submitting a todo when the input field is blank. The problem is when I load the page and the first thing I do is I click inside the input field and press enter, then the blank todo is added the Todo list. However, after that the validation works. I know there are other ways of doing this, but I want to know why this bug exists and how to fix it.
My html below
<form ng-submit="addTodo()">
<input ng-model="todoText" placeholder="Add a todo here" type="text" />
<input class="button" type="submit" value="add">
</form>
My js file
$scope.addTodo = function() {
var text = $scope.todoText;
if (text != "") {
$scope.todos.push({text:$scope.todoText, done:false});
$scope.todoText = '';
}
};
$scope.todoText is undefined , so it passes your condition and then is set to empty string '', based on your model's variables
either do if (!$scope.todoText) { or initialize it to empty string $scope.todoText = '';
in controller:
$scope.todoText = '';
$scope.addTodo = function() {
if ($scope.todoText != "") {
$scope.todos.push({text:$scope.todoText, done:false});
$scope.todoText = '';
}
};
Have you tried using the required attribute in the input?
<input type="text"
ng-model="todoText"
required <------------- prevents submission and marks the view as invalid
size="30"
placeholder="add new todo here" />
Have a try at http://jsfiddle.net/hbulhoes/uBXfN/

Categories

Resources