I am trying to validate the length of ID value in userForm in Angular14, I tried for
if(this.userForm.value.id.length < 6 || this.userForm.value.id.length >9){
console.log("length error")
}
But this is not giving the expected result. the above snippet is working for != and = only.
How can I validate this value for the range.
Adding the .ts and .html snippets for the better understanding.
component.ts
userSubmit(){
console.log(this.userForm.get('image').value);
console.log(this.userForm.value);
const formData = new FormData();
formData.append('image', this.images);
formData.append('id', this.userForm.value.id);
formData.append('des', this.userForm.value.des);
formData.append('name', this.userForm.value.name);
if(this.userForm.value.id.length < 6 || this.userForm.value.id.length > 9){
console.log("length error")
}
component.html
<div class="container">
<div *ngIf="errorMsg" class="alert alert-danger alert-dismissible fade show" role="alert">
<strong>{{errorMsg}}</strong>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<form [formGroup]="userForm" >
<div class="col-lg-4 mt-2" >
<label>Employee ID:</label>
<input type="number" class="form-control" formControlName="id" [(ngModel)]="id">
</div>
<div class="col-lg-4 mt-2" *ngIf="!getParamId" >
<button class="btn btn-primary btn-sm" [disabled]="!name || !des ||!photo||!id" (click)="userSubmit()">
Submit!!
</button>
</div>
<div class="col-lg-4 mt-2" *ngIf="getParamId" >
<button class="btn btn-dark btn-sm" (click)="userUpdate()" >
Update
</button>
</div>
</form>
</div>
From what I understand from your question, you are performing the validation for id with the length within a range.
The problem is currently your id is not a string, but it is a number.
<input type="number" class="form-control" formControlName="id" [(ngModel)]="id">
Hence you can't use .length as this property doesn't exist in the number value.
Change the <input> element from type="number" to type="text" or without type. (By default type is text).
Since you are using the Reactive form, you don't need the [(ngModel)].
<input type="text" class="form-control" formControlName="id" />
Add Validators.minLength() and Validators.maxLength() validators to id form control.
import { Validators } from '#angular/forms';
this.userForm = this.fb.group({
id: [
'',
[Validators.required, Validators.minLength(6), Validators.maxLength(9)],
],
// Following controls
});
Note: If you want the id input to be numeric characters, you need Validators.pattern():
Validators.pattern('[0-9]+')
Or validate with the length as well, so the Validators.minLength() and Validators.maxLength() can be omitted.
Validators.pattern('[0-9]{6,9}')
To disable the submit button when there is any control(s) that failed the validation:
<button
class="btn btn-primary btn-sm"
[disabled]="idHasError /* or other form controls */"
(click)="userSubmit()"
>
Submit!!
</button>
And implementing the getter.
get idHasError() {
return this.userForm.controls.id.errors;
}
Implement the getter method(s) for the rest form control(s) to return a boolean value that the form control has errors or not.
Demo # StackBlitz
Related
I'm using below FormulateForm to have input field with the submit button:
<div class="col-12 col-md-3">
<FormulateInput
name="product_codes"
label="Style number"
placeholder="Style number"
/>
</div>
<div class="col-12 col-md-3">
<button
type="button"
class="btn btn-primary"
#click="syncProducts"
>
Sync
</button>
</div>
I want to sent this input data to BE as an array:
<script>
export default {
name: 'SyncProducts',
data() {
return {
styleCodes: [],
}
},
}
</script>
But with this code, instead of Array of String, it sends it as a String.
I have created two text boxes and wrote the JSfunction to give alert msg that both the boxes together should be of 50 characters. Function called in onclick() event in Submit button. Also in controller Store() function, save the content of these two text boxes and validated with "required", then redirected to another page.
Problem is, if I give less than 50 characters it shows alert msg, but store the data even less than 50 characters given and redirected to specified page. If i give less than 50 characters, after showing the alert msg, it has to be in the same page until i give together 50 characters. It should ave the textboxes content only if more than 50 characters. Can anyone help me?
In create.blade.php
<form method="post" action="{{route('training.applicants.aim.create.process', $request->training_request_id)}}">
<div class="form-group" id="goal_group" >
<label class="col-form-label font-weight-bold" for="ziele[1]">Ziele 1</label>
<input type="text" name="ziele[1]" class="form-control form-control-sm #error('ziele.1') is-invalid #enderror" id="ziele.1" >
#error('ziele.1') <div class="invalid-feedback">{{ $errors->get('ziele.1')[0] }}</div> #enderror
</div>
<div class="form-group">
<label class="col-form-label font-weight-bold" for="ziele[2]">Ziele 2</label>
<input type="text" name="ziele[2]" class="form-control form-control-sm #error('ziele.2') is-invalid #enderror" id="ziele.2" >
#error('ziele.2') <div class="invalid-feedback">{{ $errors->get('ziele.2')[0] }}</div> #enderror
</div>
<div id="additional_goals"></div>
<hr/>
<div class="form-group row container-fluid" >
<div class="col">
<div class="col-2 float-right">
<br>
<button type="submit" style="position: absolute; right:0" class="btn btn-sm btn-primary" id="submit_btn" onclick="goal_validation()"> Submit </button>
</div>
</div>
</form>
Js function:
function goal_validation()
{
var l1=document.getElementById('ziele.1').value;
var l2=document.getElementById('ziele.2').value;
var Total=50-(l1.length +l2.length);
if(Total<50 && Total>0)
{
alert("U have to give minimum "+Total+" characters");
}
}
In controller store function:
public function storeGoals(TrainingRequest $antrag, Request $request)
{
$request->validate([
//'ziele.*' => 'required|string',
'ziele.1' => 'required|string',
'ziele.2' => 'required|string',
]);
$antrag->goals = isset($request->ziele) ? $request->ziele : NULL;
$antrag->save();
return redirect()
->route('Training.participation.mein', $request)
->with('Message', $Message);
}
You can try use strlen() function to find character length.
$request->validate([
//'ziele.*' => 'required|string',
'ziele.1' => 'required|string',
'ziele.2' => 'required|string',
]);
length1= strlen($request->ziele.1);
length2= strlen($request->ziele.2);
if((length1+length2) >= 50){
$antrag->goals = isset($request->ziele) ? $request->ziele : NULL;
$antrag->save();
return redirect()
->route('Training.participation.mein', $request)
->with('Message', $Message);
}
else{
return redirect()->back();
}
When the button is pressed, we clone the email field. Checkbox values conflict. How can I solve this problem? I would be glad if you help. I hope I can.
$('.add-extra-email-button').click(function() {
$('.clone_edilecek_email').clone(true, true).appendTo('.clone_edilen_email');
$('.clone_edilen_email .clone_edilecek_email').addClass('single-email remove-email');
$('.single-email').append('<div class="btn-delete-branch-email"><button class="remove-field-email btn btn-danger"><i class="fas fa-trash"></i></button></div>');
$('.clone_edilen_email > .single-email').attr("class", "remove-email");
$('.clone_edilen_email input').each(function() {
if ($(this).val() == "") {
$(".add-extra-email-button").attr("disabled", true);
} else {
$(".add-extra-email-button").attr("disabled", true);
}
$(".remove-email:last").find('.email-address').val('');
});
});
<div class="col-md-6">
<div class="clone_edilecek_email">
<div class="form-group">
<label for="name">E-posta</label>
<div class="input-group">
<input type="email" class="form-control email-address" name="email[]" placeholder="E-Posta giriniz">
<div class="btn-group btn-group-toggle" data-toggle="buttons">
<label class="btn btn-secondary">
<input type="checkbox" name="ban[]" value="1" autocomplete="off">
<span class="fas fa-ban"></span>
</label>
<label class="btn btn-secondary">
<input type="checkbox" name="circle[]" autocomplete="off">
<span class="fas fa-exclamation-circle"></span>
</label>
</div>
</div>
</div>
</div>
<div class="text-left">
<button type="button" class="add-extra-email-button btn btn-success" disabled><i class="fas fa-plus"></i></button>
</div>
<div class="clone_edilen_email"></div>
</div>
you must set the index between the brackets, like this:
<input type="checkbox" name="circle[0]" autocomplete="off"> <span class="fas fa-exclamation-circle"></span>
Why? otherwise only the selected checkboxes will be send and the backend. The browser will only send that 2 checkboxes are checked to the backend/server. the server than has no idea which of the checkbox indexes where checked. thats why in the frontend you need to provide an index for each checkbox.
Warning: not all backends understand these kind of form names (but most do).
you could do this like this::
var index =1;
$('input').each(function(inputElement) {
// execute the function for each input element. (might want to do the same for select elements.
// take the name of that element
var name = $(inputElement).prop('name');
// replace [] with the index you want// (warning this only works if you dont use multi dimensional arrays.
var newName = name.relace('[]','['+index+']');
// replace the old name with the new name.
$(inputElement).prop('name',newName);
});
note you can use a function like this:
function setIndeces(container, index){
$('input',container).each(function(inputElement){
var name = $(inputElement).prop('name');
var newName = name.relace('[]','['+index+']');
$(inputElement).prop('name',newName);
});
}
setIndeces($('newAddedDiv', 1);
This is my html code: this is my input filed where i have declare input type and id.
<div class="col-lg-4 col-sm-6">
<div class="form-group">
<div>
<input id="SkillsAndInterests" class="form-control" type="text"
name="SkillsAndInterests" style="width:286px;height:35px;" />
</div>
</div>
</div>
This is my js code :
vm.CommunityMembersAdditionalInfoData.SkillsAndInterests = vm.skillsandinterestarray;
$('#SkillsAndInterests').tagSuggest({
data: vm.CommunityMembersAdditionalInfoData.SkillsAndInterests,
sortOrder: 'name',
maxDropHeight: 200,
name: 'SkillsAndInterests'
});
And this is my reset function: where i am unable reset filed
vm.ResetSerachMembers = function () {
$("#SkillsAndInterests").val('');
}
And this is my button where i am calling reset function:
<button class="btn btn-danger" ng-disabled="data.isMembersLoading"
ng-click="data.ResetSerachMembers();" type="button">
Reset
</button>
I am trying to edit and delete a data in Mongo.Collection. I have a document with a number of fields including an email address.
I check while updating the data if email exists just update the email else first create a user with that email using Accounts.createUser and then update the data. Although the data is being updated successfully in the database but showing it using the helpers is not working properly. I am trying to fill the form with the saved values, either form comes half-filled, or completely-filled(usually in the first edit attempt) or completely empty. I cannot understand the reason behind this beviour.
The form template
<template name="addUnit">
<div class="modal fade" id="addUnitModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">{{#if isEdit}}Edit {{else}}Add {{/if}}Unit</h4>
</div>
{{#if tenantError}}
<div class="alert alert-danger" role="alert">{{tenantError}}</div>
{{/if}}
<form class="frmUnit" id="frmUnit">
<div class="modal-body">
<input class="form-control" type="text" placeholder="Unit Name" name="unitName" value="{{selectedUnit.unitName}}"/>
<input class="form-control" type="number" placeholder="Number of Residents" name="residents" value="{{selectedUnit.residents}}"/>
<input class="form-control" type="number" placeholder="Area sqft." name="area" value="{{selectedUnit.area}}"/>
<input class="form-control" type="text" placeholder="Primary Tenant" name="primaryTenant" value="{{selectedUnit.primaryTenant}}"/>
<input class="form-control" type="email" name="tenantEmail" placeholder="Tenant's Email" value="{{selectedUnit.tenantEmail}}"/>
<input class="form-control" type="password" name="tenantPassword" placeholder="Tenant's Password"/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
{{#if isEdit}}
<button type="submit" class="btnEditUnit btn btn-primary">Edit Unit</button>
{{else}}
<button type="submit" class="btnAddUnit btn btn-primary">Add Unit</button>
{{/if}}
</div>
</form>
</div>
</div>
</div>
</template>
Helpers
Template.addUnit.helpers({
isEdit: function() {
return Session.get('isEdit');
},
tenantError: function(){
return Session.get('tenantError');
},
selectedUnit: function(){
return Session.get('selectedUnit');
}
});
Events
Template.addUnit.events({
"submit .frmUnit": function(event){
event.preventDefault();
var form = event.target;
if(!Session.get('isEdit')){
console.log('adding');
Meteor.call('addUnit',
Session.get('selectedBuilding')._id,
{
unitName: form.unitName.value,
primaryTenant: form.primaryTenant.value,
tenantEmail: form.tenantEmail.value,
tenantPassword: form.tenantPassword.value,
residents: form.residents.value,
area: form.area.value
}, function(error, result) {
console.log(error, result);
if(!error){
$('#frmUnit')[0].reset();
$('#addUnitModal').modal('hide');
Session.set('tenantError', null);
}else{
Session.set('tenantError', error.reason);
}
});
}else{
console.log('editing');
Meteor.call('editUnit',Session.get('selectedUnit')._id,{
unitName: form.unitName.value,
primaryTenant: form.primaryTenant.value,
residents: form.residents.value,
area: form.area.value,
tenantEmail: form.tenantEmail.value,
tenantPassword: form.tenantPassword.value
}, function(error, result) {
if(!error) {
$('#frmUnit')[0].reset();
$('#addUnitModal').modal('hide');
}else{
Session.set('tenantError', error.reason);
}
});
}
}
});
Edit unit on the server
editUnit: function(unitId, unit){
//if the email entered already exists update the email and password
var updatedTenant = Accounts.findUserByEmail(unit.tenantEmail);
if(updatedTenant){
if(unit.tenantPassword && unit.tenantPassword !== ""){
Accounts.setPassword(updatedTenant._id, unit.tenantPassword);
}
Units.update({_id: unitId},
{
$set :{
unitName:unit.unitName,
primaryTenant:unit.primaryTenant,
residents: unit.residents,
area: unit.area,
tenantEmail: unit.tenantEmail
}
});
}else{
//if email doesn't exist already, create a new user first
var newUserId = Accounts.createUser(
{
email: unit.tenantEmail,
password: unit.tenantPassword,
profile:{
firstname: unit.primaryTenant,
lastname:"",
phone:"",
isTenant:true
}
});
if(newUserId){
Units.update({_id: unitId},
{
$set :{
unitName:unit.unitName,
primaryTenant:unit.primaryTenant,
residents: unit.residents,
area: unit.area,
tenantEmail:unit.tenantEmail
}
});
}
}
},
Session.get('selectedUnit') is being set from a different click handler, which displays the form. The value is being set correctly I can see that by logging it to the console.
'isEdit' is also being set from a click handler of a different template.
I have other forms working with the same approach, but they don't have Account creation and validation in them. Is it because of that?
Edit
Template.owner.events({
"click .editUnit":function(){
Session.set('isEdit', true);
Session.set('selectedUnit', this);
}
});
{{#each buildingUnits}}
<tr>
<td>
{{unitName}}
</td>
<td>
<span class= "editUnit list-icon glyphicon glyphicon-edit" data-target="#addUnitModal" data-toggle="modal" aria-hidden="true" style="padding-right: 4px;"></span>
<span class= "deleteUnit list-icon glyphicon glyphicon-remove" aria-hidden="true"></span>
</td>
</tr>
{{/each}}
I have tried to log this onto the console, I am getting the correct result, just after the two lines I tried to get the session back using Session.get('selectedUnit') and tried logging it to console, this also gives me the correct result, which means session is being successfully set.