HTML AngularJs CSS Form submit - html

I'm having a problem when I submit the form.
So.. I fill all data on the formulary then I click save... The data is correctly saved, but after the submit, the fields are cleaned and then the inputs receive the css because the form is already submitted. I would like to don't keep the formulary 'submitted' when it is correctly saved.
My code is going bellow.
HTML code
<form name="citizenForm" ng-submit="citizensCtrl.createCitizen(citizenForm)" class="css-form" novalidate>
<div class="form-group">
<label for="citizen_name">Nome *</label>
<input type="text" class="form-control" id="citizen_name" placeholder="Nome" ng-model="citizensCtrl.citizen.name" required>
<div class="form-group">
<label for="citizen_birthday">Nascimento *</label>
<uib-datepicker ng-model="citizensCtrl.citizen.birthday" class="well well-sm" datepicker-options="citizensCtrl.dateOptions" required></uib-datepicker>
</div>
<div class="form-group">
<label for="citizen_cell_phone">Celular *</label>
<input type="text" class="form-control" id="citizen_cell_phone" placeholder="Celular" ng-model="citizensCtrl.citizen.cell_phone" required>
</div>
<div class="form-group">
<label for="citizen_phone">Telefone *</label>
<input type="text" class="form-control" id="citizen_phone" placeholder="Telefone" ng-model="citizensCtrl.citizen.phone" required>
</div>
<hr>
<h4>Endereço</h4>
<div class="form-group">
<label for="citizen_address_district">Bairro *</label>
<select id="citizen_address_district" ng-model="citizensCtrl.citizen.address.district" class="form-control"
ng-options="district as district.name for district in citizensCtrl.districts" ng-change="citizensCtrl.getAddresses()" required>
<option value=""> Bairro</option>
</select>
</div>
<div class="form-group">
<label for="citizen_address_public_place">Rua *</label>
<input type="text" ng-model="citizensCtrl.citizen.address.public_place" id="citizen_address_public_place"
uib-typeahead="address as address.public_place for address in citizensCtrl.addresses | filter:{public_place: citizensCtrl.citizen.address.public_place} | limitTo:5"
typeahead-min-length="6" typeahead-select-on-exact="true"
typeahead-on-select="citizensCtrl.getZipCodes()"
typeahead-loading="loadingLocations"
ng-disabled="!citizensCtrl.citizen.address.district.id"
typeahead-no-results="noResults" class="form-control" required>
<i ng-show="loadingLocations" class="glyphicon glyphicon-refresh"></i>
<div ng-show="noResults">
<i class="glyphicon glyphicon-remove"></i> Endereço não encontrado
</div>
</div>
<div class="form-group">
<label for="citizen_address_zip_code">CEP *</label>
<select id="citizen_address_zip_code" ng-model="citizensCtrl.citizen.address.zip_code"
ng-disabled="!citizensCtrl.citizen.address.public_place.id" class="form-control"
ng-options="zip_code as zip_code.number for zip_code in citizensCtrl.zip_codes" required>
<option value="">CEP</option>
</select>
</div>
<div class="form-group">
<label for="citizen_address_number">Numero *</label>
<input type="text" class="form-control" id="citizen_address_number" placeholder="Numero" ng-model="citizensCtrl.citizen.address.number" required>
</div>
<div class="form-group">
<label for="citizen_address_complement">Complemento</label>
<input type="text" class="form-control" id="citizen_address_complement" placeholder="Complemento" ng-model="citizensCtrl.citizen.address.complement">
</div>
<input type="submit" class="btn btn-primary" value="Criar" />
<input type="reset" class="btn btn-default" ng-click="citizensCtrl.defineCitizen()" value="Limpar Formulário" />
</form>
CSS code
.css-form.ng-submitted .ng-invalid{
border: 1px solid #FA787E;
}
AngularJS controller function
self.createCitizen = function(form){
if(form.$valid){
$http.post(apiUrl + endpoint, self.citizen).then(function(response){
alertsService.add('success', 'Morador criado com sucesso!');
self.defineCitizen();
}, function(error){
alertsService.add('danger', 'Oops.. Alguma coisa deu errado. Contate o administrador.');
});
}else{
alertsService.add('danger', 'Você precisa preencher todos os campos obrigatórios.');
}
};

I used form.$setPristine(); on create function
self.createCitizen = function(form){
if(form.$valid){
$http.post(apiUrl + endpoint, self.citizen).then(function(response){
alertsService.add('success', 'Morador criado com sucesso!');
form.$setPristine();
self.defineCitizen();
}, function(error){
alertsService.add('danger', 'Oops.. Alguma coisa deu errado. Contate o administrador.');
});
}else{
alertsService.add('danger', 'Você precisa preencher todos os campos obrigatórios.');
}
};
It works perfectly for me.
Thank you all

Related

INPUT DATE VALUE ANGULAR

SERVICE.TS
addP(nome: string, cognome: string, anno_n: string): Observable<any> {
return this.http.post<Partecipanti>(this.partecipantiUrl, {
nome: nome,
cognome: cognome,
anno_n: anno_n
}, this.httpOptions).pipe(
tap((newPartecipante: Partecipanti) => this.log(`partecipante aggiunto w/ id=${newPartecipante.id}`)),
catchError(this.handleError<Partecipanti>('addP'))
);
}
COMPONENT.TS
add(nome: string, cognome: string, anno_n: string): void {
this.PartecipantiService.addP(nome, cognome, anno_n).subscribe(res => {
console.log(res);
this.loadUser();
})
}
<form class="row row-cols-lg-auto g-3 align-items-center float-center" (ngSubmit)="add(nome.value, cognome.value, anno_n.value)" (ngSubmit)="loadUser()" style="justify-content: center;">
<div class="col-12">
<label class="visually-hidden" for="inlineFormInputGroupUsername">Nome</label>
<div class="input-group">
<input type="text" class="form-control" id="inlineFormInputGroupUsername" required #nome placeholder="Nome">
</div>
</div>
<div class="col-12">
<label class="visually-hidden" for="inlineFormInputGroupUsername">Cognome</label>
<div class="input-group">
<input type="text" class="form-control" id="inlineFormInputGroupUsername" required #cognome placeholder="Cognome">
</div>
</div>
<div class="col-12">
<label class="visually-hidden" for="inlineFormInputGroupUsername">Data di nascita</label>
<div class="input-group">
<input type="text" class="form-control" id="inlineFormInputGroupUsername" required #anno_n useValueAsDate placeholder="Data di nascita (GG/MM/AAAA)">
</div>
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary shadow-lg">Salva</button>
</div>
</form>
How can I take the date value in my function "add"?
In my function add I have 3 field (name, surname and date), when I call my function add on a button I use (ngSubmit)="add(name.value, surname.value, date...?). What I have to use? Value is for string, I can't find something for Date! This part is on component.html Can you explain me how it works? My input is type="date"
I would suggest you use ngForm. This is the easiest for handling this scenario.
See here the Documentation: https://angular.io/api/forms/NgForm
Here is a working example i did: https://stackblitz.com/edit/angular-ivy-pqgewm?devtoolsheight=33&file=src/app/app.component.html
In Essence you want your HTML look like this:
<form #form="ngForm" (ngSubmit)="userService.submitForm(form)">
<div>
<label for="firstName">First Name</label>
<input name="firstName" id="firstName" type="text" ngModel required />
</div>
<div>
<label for="lastName">Last Name</label>
<input name="lastName" id="lastName" ngModel type="text" required />
</div>
<div>
<label for="dateOfBirth">Date of Birth</label>
<input name="dateOfBirth" id="dateOfBirth" ngModel type="date" required />
</div>
<br />
<button type="submit">Submit</button>
</form>
And your Submit function to look like this:
submitForm(form: NgForm) {
if (form.valid) {
const user: User = {
name: form.value['firstName'],
surname: form.value['lastName'],
birth: new Date(form.value['dateOfBirth']),
};
}
}

Use wtfroms without using flask-bootstrap

I'm starting to create a login-signup web page for a project and for that I would like to use "wtforms" but I can't find any examples without using the flask-bootstrap library.
Can I use wtform without flask-bootstrap?
I did some experiments but it doesn't seem to work.
This is my code:
HTML:
<div class="login-form">
<form action="/registration" method="POST">
<h2 class="text-center">Registrazione</h2>
<div class="form-group has-error">
<input type="text" class="form-control" name="nome" placeholder="Nome" required="required">
</div>
<div class="form-group has-error">
<input type="text" class="form-control" name="cognome" placeholder="Cognome" required="required">
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" placeholder="E-mail" required="required">
</div>
<div class="form-group">
<input type="password" class="form-control" name="password" placeholder="Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="la password deve contenere almeno un numero, una lettera maiuscola, una minuscola e deve essere almeno di 8 carateri" required="required">
</div>
<div class="form-group">
<input type="password" class="form-control" name="confermaPsw" placeholder="Conferma password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="la password deve contenere almeno un numero, una lettera maiuscola, una minuscola e deve essere almeno di 8 carateri" required="required">
</div>
<div class="form-group">
<select class="form-control" name="ruolo" id="sel1" required="required">
<option>SW</option>
<option>PM</option>
<option>PE</option>
</select>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg btn-block">Registrati</button>
</div>
</form>
Python:
class RegisterForm(FlaskForm):
name = StringField('name', validators=[InputRequired(), Length(min=4, max=15)])
surname = StringField('surname', validators=[InputRequired(), Length(min=4, max=15)])
email = StringField('email', validators=[InputRequired(), Length(max=50)])
password = PasswordField('password', validators=[InputRequired(), Length(min=8, max=80)])
ruolo = StringField('urole', validators=[InputRequired()])
#app.route('/registration', methods=['POST', 'GET'])
def registration():
# se tutti gli input rispettano i prerequisiti di validazione, aggiungi utente
form = RegisterForm()
if request.method == 'POST':
if form.validate_on_submit():
hashed_password = generate_password_hash(form.password.data, method='sha256')
new_user = User(name=form.nome.data, surname=form.cognome.data, email=form.email.data, password=hashed_password, urole=form.ruolo.data)
db.session.add(new_user)
db.session.commit()
return '<h1>New user has been created!</h1>'
return '<h1>post send but no validate!</h1>'
return render_template("registration.html", form=form)
EDIT: I need to have the same formatting I had before using WTForms
I'm looking for a solution for this exact question too, but all use flask-bootstrap and that is exactly what I don't want to use.
I've tried the following:
{{ form.firstname(class='form-control bg-white border-left-0 border-md', placeholder='Firstname') }}
outputs
<input class="form-control bg-white border-left-0 border-md" id="firstname" name="firstname" placeholder="Firstname" required type="text" value="">
This seems to work, well visually it seems to do what I want.

How to confirm to matching email fields?

I'm creating a "Event Form" where people should be able to sign-up for comming events.
I added two fields for email. One for them to write their email in and the second one to confirm the email.
I want them to write it twice to ensure that we are getting the right email.
When the email in field 2 (Bekräfta Email) is wrong they should get an error message.
But it seems like I'm doing something wrong with the code.
This is the HTML-Code:
<script type="text/javascript">
function openTerms(id) {
var terms = {"1":"Med detta villkor godkännes att Svenska Bostadsfonden Management AB får använda min personliga information så som,namn, telefonnummer, mail, arbetstitel, arbetsplats, postadress och besöksadress i syfte att...... I enlighet med GDPR och lagen och samtycke.......","2":"Terms of conditions bla bla bla","3":null,"4":null,"5":null,"6":null,"7":null};
var preview = window.open("", "", "height=700,width=800,scrollbars=yes,resizable=yes,toolbar=no,status=no,menu=no,titlebar=no,location=no,addressbar=no");
var html="<head><meta charset=\"UTF-8\"><style>body {margin: 0; padding: 20px;color: #333;font-family: Helvetica;font-size: 14px;}</style></head><body>" + terms[id] + "</body>";
preview.document.write(html);
}
</script>
<form id="up-form" name="form_8311ud1507fd3ad2e43278424bca0e4adc3bd" action="https://power.upsales.com/api/external/formSubmit" method="POST">
<div>
<label>Jag vill beställa</label>
<br>
<label><input type="checkbox" value="Aktuellt faktablad" name="Extra.1547544176421"> Aktuellt faktablad </label>
<label><input type="checkbox" value="Aktuell broschyr" name="Extra.1547544176421"> Aktuell broschyr </label>
</div>
<div>
<label>Jag vill beställa i egenskap av</label>
<br>
<select name="Extra.1547544378077">
<option></option>
<option value="Befintlig kund">Befintlig kund</option>
<option value="Intresserad investerare">Intresserad investerare</option>
<option value="Finansiell rådgivare">Finansiell rådgivare</option>
<option value="Media/analytiker">Media/analytiker</option>
<option value="Annat">Annat</option>
</select>
</div>
<div>
<label>Namn *</label>
<br>
<input maxlength="512" type="text" name="Contact.name" required="required">
</div>
<div class="email">
<label>Email *</label>
<br>
<input maxlength="512" type="email" id="up-email-input" autocomplete="off" name="Contact.email" required="required">
</div>
<div>
<label>Bekräfta Email *</label>
<br>
<input maxlength="512" type="text" name="Extra.1547643200666" required="required">
</div>
<div>
<label>Telefon *</label>
<br>
<input maxlength="512" type="text" id="up-client-name-input" name="Client.name" required="required">
</div>
<div>
<label>Postadress *</label>
<br>
<input maxlength="512" type="text" name="Extra.1547544152076" required="required">
</div>
<!-- REQUIRED FIELDS -->
<input type="hidden" name="formCid" value="8311">
<input type="hidden" name="formId" value="8311ud1507fd3ad2e43278424bca0e4adc3bd">
<input type="hidden" name="isFrame" value="false">
<input type="text" value="" name="validation" style="display: none;">
<!-- END OF REQUIRED FIELDS -->
<button type="submit">Skicka</button>
</form>
<script src="https://img.upsales.com/2XybO6NW9Y+uyQU9cm4CLw==/be.js"></script>
I added the following to the code:
<div class="email">
<label>Email *</label>
<br>
<input maxlength="512" type="email" id="up-email-input" autocomplete="off" name="Contact.email" required="required">
</div>
<div>
<label>Bekräfta Email *</label>
<br>
<input maxlength="512" type="text" name="Extra.1547643200666" required="required">
</div>
if (trim($fv->txt_Bekräfta Email) != $fv->txt_Email) {
$e->defineError("invalid_email", "Your Email address do not match", "txt_Bekräfta Email");
Seems like the following sequence does not work:
if (trim($fv->txt_Bekräfta Email) != $fv->txt_Email) {
$e->defineError("invalid_email", "Your Email address do not match", "txt_Bekräfta Email");

Text area placeholder is not showing up while having no space or newline between opening and closing tags

My text area place holder is not showing up. All previous answers I have seen here describe there should be no space or new line between opening and closing tags of text area and my code don't have both. Is data-validation-required-message is creating problem ? How can I solve this.
Here is my code:
<div class="col-md-6">
<div class="form-group">
<textarea class="form-control" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea>
<p class="help-block text-danger"></p>
</div>
I go and try
<textarea class="form-control" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea>
But it`s work for me !:S
It works, check the snippet:
Demo: https://reactiveraven.github.io/jqBootstrapValidation/
$(function() {
prettyPrint();
$("input,textarea,select").jqBootstrapValidation(
{
preventSubmit: true,
submitError: function($form, event, errors) {
// Here I do nothing, but you could do something like display
// the error messages to the user, log, etc.
},
submitSuccess: function($form, event) {
alert("OK");
event.preventDefault();
},
filter: function() {
return $(this).is(":visible");
}
}
);
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
<link rel="stylesheet" href="https://reactiveraven.github.io/jqBootstrapValidation/css/prettify_bootstrap.css">
<link rel="stylesheet" href="https://reactiveraven.github.io/jqBootstrapValidation/css/bootstrap.css">
<script src="https://reactiveraven.github.io/jqBootstrapValidation/js/jQuery-1.7.2-min.js"></script>
<script src="https://reactiveraven.github.io/jqBootstrapValidation/js/bootstrap.js"></script>
<script src="https://reactiveraven.github.io/jqBootstrapValidation/js/prettify.js"></script>
<script src="https://reactiveraven.github.io/jqBootstrapValidation/js/jqBootstrapValidation.js"></script>
<form class="form-horizontal" novalidate>
<div class="control-group">
<label class="control-label" for="email">Email address</label>
<div class="controls">
<input type="email" name="email" id="email" required>
<p class="help-block">Email address we can contact you on</p>
</div>
</div>
<div class="control-group">
<label class="control-label" for="emailAgain">Email again</label>
<div class="controls">
<input type="email" data-validation-matches-match="email" data-validation-matches-message="Must match email address entered above" id="emailAgain" name="emailAgain">
<p class="help-block">And again, to check for speeling miskates</p>
</div>
</div>
<div class="control-group">
<label class="control-label" for="terms-and-conditions">Legal</label>
<div class="controls">
<label class="checkbox">
<input type="checkbox" id="terms-and-conditions" name="terms-and-conditions" required data-validation-required-message="You must agree to the terms and conditions">
I agree to the terms and conditions
</label>
<p class="help-block"></p>
</div>
</div>
<div class="control-group">
<label class="control-label">Quality Control</label>
<div class="controls">
<label class="checkbox">
<input type="checkbox" name="qualityControl[]" value="fast" data-validation-minchecked-minchecked="2" data-validation-minchecked-message="Choose two" data-validation-maxchecked-maxchecked="2" data-validation-maxchecked-message="You can't have it all ways" >
Fast
</label>
<label class="checkbox">
<input type="checkbox" name="qualityControl[]" value="cheap">
Cheap
</label>
<label class="checkbox">
<input type="checkbox" name="qualityControl[]" value="good">
Good
</label>
<p class="help-block"></p>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Test Validation <i class="icon-ok icon-white"></i></button><br />
</div>
</form>
Note
Now if you want to display this message Please enter a message. then you have to validate this using jQuery. Because its data-validation-required-message is used to display custom validation message.

Validation of angular form without submit button

I am using anuglar.js form validation.
I want to check validation without form submit button.
This is my html.
<form name="userForm">
<input type="hidden" ng-model="StandardID" />
<div class="form-group">
<label for="email">Name:</label>
<input type="text" class="form-control" ng-model="Name" placeholder="Name" maxlength="50" required>
<span ng-show="userForm.Name.$dirty && !userForm.Name.$valid">Name is required.</span>
</div>
<div class="form-group">
<label for="pwd">Alias:</label>
<input type="text" class="form-control" ng-model="Alias" placeholder="Alias" maxlength="50" required>
</div>
<button type="submit" class="btn btn-info" ng-click="update()">Submit</button>
<button type="submit" class="btn btn-info" data-dismiss="modal">Cancel</button>
</form>
My controller js is.
$scope.update= function () {
alert($scope.userForm.Name.$valid);
if ($scope.userForm.Name.$valid) {
alert("Entry added");
}
}
It shows small dialog that says this field is required. I don't want this popup . Why span section does not show?
To do it, the key is use the name attribute in your <form> and in all of your inputs.
Following this way, angularjs will create a form instance where you can access all fields like myForm.myInput.$invalid
For example:
<form name="myForm" novalidate>
<label>My Input:</label>
<input type="text" name="myInput" ng-model="myInput" required>
<span ng-show="myForm.myInput.$dirty && myForm.myInput.$invalid">My Input is invalid.</span>
</form>
Check angular docs
HTML
<div ng-app="myApp">
<form name="cutome_form" ng-submit="submitForm()" novalidate>
<input type="text" name="name" class="form-control" ng-model="Name" placeholder="Name" maxlength="50" required>
<div ng-show="cutome_form.name.$dirty && cutome_form.name.$invalid">
<span class="error" ng-show="cutome_form.name.$error.required">The field is required.</span>
</div>
<div class="form-group">
<label for="pwd">Alias:</label>
<input type="text" name="alias" class="form-control" ng-model="Alias" placeholder="Alias" maxlength="50" required>
</div>
<div ng-show="cutome_form.alias.$dirty && cutome_form.alias.$invalid">
<span class="error" ng-show="cutome_form.alias.$error.required">The field is required.</span>
</div>
<button type="submit" ng-disabled="cutome_form.$invalid">Submit All</button>
</form>
</div>
directive
.directive('ngModel', function() {
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel) {
elem.on('blur', function() {
ngModel.$dirty = true;
scope.$apply();
});
ngModel.$viewChangeListeners.push(function() {
ngModel.$dirty = false;
});
scope.$on('$destroy', function() {
elem.off('blur');
});
}
}
});