I have a html form and I am using angular JS for validation. Here, after submitting the form I am calling the reset method which will reset the form input fields to default.
But, when I submit and call reset method, the validation messages appears in the input field. I have used the below code. I don't want to see the validation messages after submitting the form.
HTML
<form name="createvalidation" role="form" class="col-lg-12" novalidate>
<div class="form-group">
</div>
<div class="form-group">
<input type="text" placeholder="Challenge name" class="form-control input-sm" name="name" ng-model="challenge.challengename" required>
<span ng-show="(createvalidation.name.$dirty || submitted) && createvalidation.name.$error.required">Name is reqiured</span>
</div>
<div class="form-group">
<textarea class="form-control input-sm" rows="2" placeholder="Write more about this challenge..." name="description" ng-model="challenge.challengedescription" required></textarea>
<span ng-show="(createvalidation.description.$dirty || submitted) && challengecreatevalidation.description.$error.required">Description is reqiured</span>
</div>
</form>
<div>
<button type="button" ng-click="createChallenge()">Create</button>
</div>
JS CODE
$scope.createChallenge = function() {
//get the field and store in db
$scope.resetForm();
}
$scope.master = {};
$scope.resetForm = function() {
$scope.challenge = angular.copy($scope.master);
$scope.createvalidation.$setPristine();
}
$scope.createChallenge = function() {
//get the field and store in db
$scope.resetForm();
}
$scope.master = {};
$scope.resetForm = function() {
$scope.submitted = false; //Try adding this
$scope.challenge = angular.copy($scope.master);
$scope.createvalidation.$setPristine();
}
You appear to be copying the pristine state of the form from within the resetForm function. This means that it will only have the version of the form when resetForm is called. Instead perhaps you should be doing that copy whenever the form is setup and pristine.
Related
I have a simple input params that are required. I want to disable my submit button until all the required fields are satisfied. Granted I am new to django, and the particular code I am working on is very old. As a result, post like this or this are not helping.
Current code that I am trying from one of the posts linked and including my own template
<script type="text/javascript">
$(document).ready(function() {
validate();
$('input').on('keyup', validate);
});
function validate() {
var inputsWithValues = 0;
// get all input fields except for type='submit'
var myInputs = $("input:not([type='submit'])");
myInputs.each(function(e) {
// if it has a value, increment the counter
if ($(this).val()) {
inputsWithValues += 1;
}
});
if (inputsWithValues == myInputs.length) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
$('#submit').on('click', function() {
var zip = $('#zip').val();
var email = $('#email').val();
var name = $('#name').val();
//if inputs are valid, take inputs and do something
});
<form class="form-horizontal" action="" method="get" id="dataform">
<div class="form-group">
<div class="container">
<div class="row">
<div class="col-md-offset-2 col-md-3">
<input class="col-md-12" id="zip" type="text" placeholder="Enter zip code" aria-required="true">
</div>
<div class="col-md-3">
<input class="col-md-12" id="name" type="text" placeholder="Enter last name" aria-required="true">
</div>
<div class="col-md-3">
<input class="col-md-12" id="email" type="email" placeholder="Enter email address" aria-required="true">
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="btn btn-primary" id="submit" type="submit">Submit</div>
</div>
</div>
</form>
any help on disabling my submit button until input fields are not validated/filled is much appreciated. Again, new to django and I am unable to use existing threads on said topic
From your current code, looks like your selector for the submit input is not actually getting the submit "button". Currently, your template defines the submit as a div and not an input, thus your selectors should be $("div[type=submit]") not $("input[type=submit]")
Better yet, just select by div id $('#submit')
Instead of targeting attributes, I was targeting props. Below is the fix for my particular issue.
if (inputsWithValues === 3) {
$("div[type=submit]").attr("disabled", false);
} else {
$("div[type=submit]").attr("disabled", 'disabled');
}
I have a form that is supposed to register a user and I have two inputs for passwords that are supposed to be the same. I use html for the form and javascript to check if both inputs are matching. The code I'm using doesn't work though because even if the passwords are different, the user data is still sent to my console when the form shouldn't be able to submit in the first place. These are portions of my html file.
<form id="registration-info" method="POST" action="/registration" onsubmit="return validatePassword();">
....
<div class="mb-3">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" id="password" required>
<div class="invalid-feedback">
Please enter a password.
</div>
</div>
<div class="mb-3">
<label for="repeat_password">Repeat Password</label>
<input type="password" class="form-control" name="repeat_password" id="repeat_password"required>
<script language='javascript' type='text/javascript'>
var password = document.getElementById("password")
, repeat_password = document.getElementById("repeat_password");
function validatePassword(){
if(password.value != repeat_password.value) {
document.repeat_password.setCustomValidity("Passwords Don't Match");
} else {
document.repeat_password.setCustomValidity('');
}
}
</script>
</div>
You have a few mistakes there you'll need to fix up.
Use a JavaScript event listener and remove document..
form = document.getElementById("registration-info");
form.onclick = function() {
var password = document.getElementById("password");
var repeat_password = document.getElementById("repeat_password");
if(password.value != repeat_password.value) {
repeat_password.setCustomValidity("Passwords Don't Match");
} else {
document.repeat_password.setCustomValidity('');
}
}
You do not need to use document. when references variables you have set. Using a JavaScript event listener helps you write clean code, that separates UI and logic.
I'm trying to create a form where, if the user selects 'yes' from a dropdown, two extra fields appear. Both of these fields are required, and one of them needs to be validated according to an array of 'codes' - the user must input one of the codes in the array for the form to submit correctly. However, if the user selects 'no' from the dropdown, these fields do not appear and are not required, and the array validation does not occur and the form can be submitted.
I have some code for this, however I can't get the fields to appear. An earlier issue I encountered with this (minus the array validation - including that broke the code and stopped the extra fields appearing) was that if the user selected 'yes', and then went back to change their mind and selected 'no', then the form would not submit, clearly still requiring the fields to be filled in/correct array value inputted.
If anyone could help me in making this work I would greatly appreciate it.
HTML:
<form id="form" method="post" action="action.php">
<div class="form-group">
<label class="control-label">Defect?</label>
<select onclick='checkIfYes()' class="select form-control" id="defect" name="defect">
<option id="No" value="No">No</option>
<option id="Yes" value="Yes">Yes</option>
</select>
</div>
<div id="extra" name="extra" style="display: none">
<label class="control-label" for="desc">Description</label>
<input class="form-control" type="text" id="desc" name="desc" required disabled>
<label class="control-label" for="auth_by">Authorised By</label>
<input class="form-control" type="text" id="auth_code_input" name="auth_by" required disabled>
</div>
<hr>
<div class="form-group">
<button class="btn btn-info" id="submit" name="submit" type="submit">Submit
</button>
</div>
</form>
JavaScript:
$(document).ready(function() {
checkIfYes = function checkIfYes() {
if (document.getElementById('defect').value == 'Yes') {
// show extra fields & make them required
document.getElementById('extra').style.display = '';
document.getElementById('auth_code_input').disabled = false;
document.getElementById('desc').disabled = false;
// show user if their input is one of the codes in the array when leaving field
$('#auth_code_input').blur(function() {
if (!ValidateInput()) {
e.preventDefault();
}
});
// prevent form submission if input is not one of the codes in the array
$('#auth_form').on('submit', function(e) {
if (!ValidateInput()) {
e.preventDefault();
}
});
function ValidateInput() {
var codes = ['Foo', 'Bar']; // user must enter one of these
var IsValid = false;
var input = $('#auth_code_input').val()
if (codes.indexOf(input) > -1) { // if input equals one of the codes in the array
$('#iconBad').removeClass('glyphicon-remove').addClass('glyphicon-ok');
IsValid = true;
} else {
$('#iconBad').removeClass('glyphicon-ok').addClass('glyphicon-remove');
IsValid = false;
}
return IsValid;
}
} else { // hide and disable extra fields so form can submit
document.getElementById('extra').style.display = 'none';
document.getElementById('auth_code_input').disabled = true;
document.getElementById('desc').disabled = true;
}
}
});
JSFiddle
It's a glitch in the way you define the function -- by calling checkIfYes() it's looking for it on the global (window's) scope. By changing the line:
function checkIfYes() {...
to this:
checkIfYes = function() {...
then you've got it on the global scope. Which is, by the way, bad practice. You'd be better to create a click handler in your script itself, than to hard- code the function call in your HTML. But that's just me.
A few changes made, some pretty significant -- first, I removed the hard-coded reference to checkIfYes and simply put the event in your javascript. Second (and pretty darn significant), I moved the event handlers to the root of your javascript, rather than defining them in your checkIfYes function. This way, they don't depend on that being called each time. Try it, it works.
$(document).ready(function() {
/**
* Define some custom events to handle...
**/
$("#defect").on("change", checkIfYes );
// show user if their input is one of the codes in the array when leaving field
$('#auth_code_input').blur(function() {
if (!ValidateInput()) {
console.log("Input is wrong!");
}
});
// prevent form submission if input is not one of the codes in the array
$('#auth_form').on('submit', function(e) {
e.preventDefault();
console.log("This is where I would be checking...");
if (ValidateInput()) {
$("#auth_form").submit();
}
});
// Utility Functions.
function checkIfYes() {
if (document.getElementById('defect').value == 'Yes') {
// show extra fields & make them required
document.getElementById('extra').style.display = '';
document.getElementById('auth_code_input').disabled = false;
document.getElementById('desc').disabled = false;
} else { // hide and disable extra fields so form can submit
document.getElementById('extra').style.display = 'none';
document.getElementById('auth_code_input').disabled = true;
document.getElementById('desc').disabled = true;
}
}
function ValidateInput() {
var codes = ['Foo', 'Bar']; // user must enter one of these
var IsValid = false;
var input = $('#auth_code_input').val()
if (codes.indexOf(input) > -1) { // if input equals one of the codes in the array
$('#iconBad').removeClass('glyphicon-remove').addClass('glyphicon-ok');
IsValid = true;
} else {
$('#iconBad').removeClass('glyphicon-ok').addClass('glyphicon-remove');
IsValid = false;
}
return IsValid;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form" method="post" action="action.php">
<div class="form-group">
<label class="control-label">Defect?</label>
<select class="select form-control" id="defect" name="defect">
<option id="No" value="No">No</option>
<option id="Yes" value="Yes">Yes</option>
</select>
</div>
<div id="extra" name="extra" style="display: none">
<label class="control-label" for="desc">Description</label>
<input class="form-control" type="text" id="desc" name="desc" required disabled>
<label class="control-label" for="auth_by">Authorised By</label>
<input class="form-control" type="text" id="auth_code_input" name="auth_by" required disabled>
</div>
<hr>
<div class="form-group">
<button class="btn btn-info" id="submit" name="submit" type="submit">Submit
</button>
</div>
</form>
I'm trying to do some basic form validation in Angular. I have the following code for my form:
<div class="col-xs-12 col-md-6" ng-controller="contactFormCtrl">
<form class="contact-form" ng-show="formVisible" novalidate>
<div class="form-group">
<label for="name">Name</label><small> Required</small>
<input type="text" class="form-control" ng-model="contact.name" id="name" placeholder="Name" required>
<div ng-show="nameEmpty">Please enter your name</div>
</div>
<div class="form-group">
<label for="email">E-mail</label><small> Required</small>
<input type="email" class="form-control" ng-model="contact.email" id="email" placeholder="E-mail" required>
<div ng-show="emailEmpty">Please enter your e-mail address</div>
</div>
<div class="form-group">
<label for="tel">Telephone</label>
<input type="text" class="form-control" ng-model="contact.tel" id="tel" placeholder="Telephone">
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" rows="5" ng-model="contact.message" required></textarea>
</div>
<input type="submit" ng-click="submit(contact)" class="btn btn-success" value="Submit">
<input type="button" ng-click="reset()" class="btn btn-primary" value="Reset">
</form>
<div ng-show="submissionSuccess">
<h4>Your message was sent successfully! We'll get back to you as soon as possible</h4>
<button class="btn btn-info" ng-click="reset()">Send another message</button>
</div>
</div>
And the following code in my controller:
$scope.contact = {};
$scope.formVisible = true;
$scope.userEmpty = false;
$scope.emailEmpty = false;
$scope.submit = function(contact) {
if (typeof $scope.contact.name != 'undefined' && typeof $scope.contact.email != 'undefined'){
$http.post('php/contact.php', contact)
.success(function(){
$scope.submissionSuccess = true
$scope.formVisible = false
})
} else if (!$scope.contact.name) {
$scope.nameEmpty = true
} else if (!$scope.contact.email) {
$scope.emailEmpty = true
}
}
The form already highlights empty or erroneously formatted fields in red, but now I'm trying to prevent submission of an invalid form too. My thought was to check if the $scope.contact.user and $scope.contact.email variables were undefined, and go from there. However, when I run this and try and submit and empty form, I get an error:
TypeError: Cannot read property 'name' of undefined
However, if I enter something in the Name field, then submit with an empty e-mail, it works as expected. This leads to think it's an initialization problem, but I thought I'd initialized the variable in the first line of my controller with $scope.contact = {}.
What am I doing wrong?
Codeschool provide full tutorial about form validation, so watch it and do it.
First button near to the will execute ng-submitt="SOMEmETHOD" in tag. Thru the name of the form get $valid property and use this condition to disabled button. also use out of box angular validation methods in form of clear and easy to use directives like ng-minlenght. For live http requests use watcher or assync
$scope.$watch('contact.email',function(newValue, oldValues){
if(newValue !== undefined){
$timeout(function(){
REQUEST.success(function(){
scope.reqs = 'this is it'
})
},600);
}
});
_.isEmpty required underscore.js
$scope.test = "Test";
angular.isUndefined($scope.test); // false
angular.isUndefined($scope.test.newField); // true
_.isEmpty($scope.test); // false
$scope.test = "";
angular.isUndefined($scope.test); // false
_.isEmpty($scope.test); // true
$scope.myObject = {};
angular.isUndefined($scope.test); // false
_.isEmpty($scope.myObject ); // true
But I see all correct in your code. If you initialize $scope.contact={} before function submit is called, the error shouldn't appear. So, or you call the function submit and after you initialize $scope.contact or in some point you overwrite the value and after you call the function.
In my from I have several inputs with validation, I need for the ng-invalid class to only be applied once the user has submitted the form.
On submit I can set a value on the scope as such...
$scope.submitForm = function () {
$scope.submited = true;
// other bits
}
... but I cant figure out how to conditionally display ng-invalid without changing the validation itself.
I am running angular 1.1.5
Demo
<input type="email" name="email" ng-model="formData.email" required />
<span ng-show="(myForm.email.$dirty || submitted) && myForm.email.$error.required">
Email is required
</span>
Use $dirty flag to show the error only after user interacted with the input:
<div ng-app>
<div ng-controller="testController">
<form name="formValidate">
<input type="text" name="testing" required ng-model="testField" ng-class="{ invalid: submitted && formValidate.testing.$invalid }"/>
<button ng-click="test()">Test</button>
</form>
</div>
</div>
<script>
var app = angular.module('', []);
function testController($scope)
{
$scope.submitted = false;
$scope.test= function()
{
$scope.submitted = true;
console.log($scope.formValidate.$invalid);
}
}
</script>
<style>
.invalid
{
border:1px solid red;
}
</style>
For custom errors I suggest to use the $setValidity method within each field.
$scope.formName.fieldName.$setValidity('custom_error_name', true);
so you will have more control over the css part too, because this kind of workflow will create also a custom class inside your field like "ng-custom_error_name" so you can deal with that.