How to validate number fields with template driven forms in Angular? - html

Is there a way to validate the numerical value of input field using template driven forms in Angular 11?
To give a bit of context, I'm building a memory card game using Angular 11 and I'd like to make sure that the player can't select a maxFlipCount that is inferior to the number of cards. I have been struggling to make this work using the min attribute on an input tag. Maybe there's another that I don't know of that doesn't use the min attribute.
How could I achieve this?
I'm trying to apply this validation to the last input tag, before the submit button in my template code. This is what I have so far:
<form #gameOptionsForm="ngForm" (ngSubmit)="startGame()" novalidate>
<!-- mode de jeu -->
<div class="field">
<label class="label">Mode de jeu</label>
<div class="control">
<div class="select" [class.is-danger]="
gameMode.invalid && (gameMode.dirty || gameMode.touched)
">
<select name="gameMode" [(ngModel)]="optionsForm.gameMode" #gameMode="ngModel" required>
<option value="1">1 joueur</option>
<option value="2">2 joueurs</option>
</select>
</div>
</div>
<p class="help is-danger" *ngIf="gameMode.invalid && (gameMode.dirty || gameMode.touched)">
Vous devez choisir un mode jeu
</p>
</div>
<!-- nom du premier joueur -->
<div class="field" *ngIf="optionsForm.gameMode == 1 || optionsForm.gameMode == 2">
<label class="label">Nom du joueur 1</label>
<div class="control">
<input [class.is-danger]="
player1.invalid && (player1.dirty || player1.touched)
" class="input" type="text" name="player1" placeholder="Joueur 1" #player1="ngModel" [(ngModel)]="optionsForm.player1" required />
</div>
<p class="help is-danger" *ngIf="player1.invalid && (player1.dirty || player1.touched)">
Veuillez entrer un nom pour le joueur 1
</p>
</div>
<!-- nom du deuxieme joueur -->
<div class="field" *ngIf="optionsForm.gameMode == 2">
<label class="label">Nom du joueur 2</label>
<div class="control">
<input [class.is-danger]="
player2.invalid && (player2.dirty || player2.touched)
" class="input" type="text" name="player2" placeholder="Joueur 2" #player2="ngModel" [(ngModel)]="optionsForm.player2" required />
</div>
<p class="help is-danger" *ngIf="player2.invalid && (player2.dirty || player2.touched)">
Veuillez entrer un nom pour le joueur 2
</p>
</div>
<!-- taille de la grille -->
<div class="field">
<label class="label">Nombre de cartes</label>
<div class="control">
<div class="select" [class.is-danger]="
gridSize.invalid && (gridSize.dirty || gridSize.touched)
">
<select name="gridSize" [(ngModel)]="optionsForm.gridSize" #gridSize="ngModel" required>
<option value="4">4</option>
<option value="16">16</option>
<option value="36">36</option>
</select>
</div>
</div>
<p class="help is-danger" *ngIf="gridSize.invalid && (gridSize.dirty || gridSize.touched)">
Vous devez choisir un nombre de cartes
</p>
</div>
<!-- nombre maximal de coups -->
<div class="field">
<label class="label">Nombre maximal de coups</label>
<div class="control">
<input [class.is-danger]="
maxFlipCount.invalid && (maxFlipCount.dirty || maxFlipCount.touched)
" class="input" type="number" name="maxFlipCount" #maxFlipCount="ngModel" [(ngModel)]="optionsForm.maxFlipCount" required min="{{ optionsForm.gridSize }}" />
</div>
<p class="help is-danger" *ngIf="
maxFlipCount.invalid &&
(maxFlipCount.dirty || maxFlipCount.touched) &&
maxFlipCount.errors.required
">
Veuillez entrer un nombre maximal de coups
</p>
<p class="help is-danger" *ngIf="maxFlipCount.errors?.min">
Veuillez entrer un nombre supérieur ou égal à {{ optionsForm.gridSize }}
</p>
</div>
<button type="submit" [disabled]="!gameOptionsForm.form.valid">
Commencer
</button>
</form>
The min attribute does actually do it's job when I use the little arrows (automatically put there by the browser) on the side to increase/decrease the value, however the problem is when I type a value in manually, the field value can be whatever I want and it will not appear as being invalid.
Thank you for reading through this and suggesting any ideas.

I ended up finding the answer to my question. So, I used a custom directive to check that the value of the field was what I wanted.
This article explains it quite well: https://www.digitalocean.com/community/tutorials/angular-custom-validation

Related

Cant update a entry in Angular

When I try to update an entry i don't have any errors but nothing happens
I dont have much idea of angular, i am sorry.
This is my html
<div class="modal-body">
Id del Envío: <input type="text" placeholder="Id del envío" id="idE" class="form-control" value="{{envioactual.idEnvio}}" disabled> <br>
Nombre del Destinatario: <input type="text" placeholder="Nombre Cliente" id="inombreDestinatario" class="form-control" value="{{envioactual.nombreDestinatario}}"> <br>
Dirección de Entrega <input type="text" placeholder="Dirección Completa" id="idireccionCompleta" class="form-control" value="{{envioactual.direccionCompleta}}"> <br>
DNI del receptor <input type="text" placeholder="DNI del receptor" id="iDNI" class="form-control" value="{{envioactual.dninif}}"> <br>
Código Postal <input type="text" placeholder="Código Postal" id="icodigoPostal" class="form-control" value="{{envioactual.codigoPostal}}"> <br>
Número de intentos de entrega <input type="text" placeholder="Número de intentos de entrega" id="inumIntentosEntrega" class="form-control" value="{{envioactual.numIntentosEntrega}}"> <br>
Estado del envío <input type="text" placeholder="Estado del envío" id="iidEstadoEnvio" class="form-control" value="{{envioactual.idEstadoEnvio}}"> <br>
Id Del Cliente<input id="prodId" id="clienteId" class="form-control" value="{{envioactual.idCliente}}" disabled> <br>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal" (click)="actualizarEnvio()">Actualizar</button>
This my 'envios' component
envioactual : Envio;
actualizarEnvio()
{
let idEnvio = parseInt((document.getElementById('idE') as HTMLInputElement).value);
let nombreDestinatario = (document.getElementById('inombreDestinatario') as HTMLInputElement).value;
let direccionCompleta = (document.getElementById('idireccionCompleta') as HTMLInputElement).value;
let codigoPostal = (document.getElementById('icodigoPostal') as HTMLInputElement).value;
let numIntentosEntrega = parseInt((document.getElementById('inumIntentosEntrega') as HTMLInputElement).value);
let idEstadoEnvio = (document.getElementById('iidEstadoEnvio') as HTMLInputElement).value;
let dninif = (document.getElementById('iDNI') as HTMLInputElement).value;
let idCliente = (document.getElementById('idCliente') as HTMLInputElement).value;
const contenido =
{
idEnvio, nombreDestinatario, direccionCompleta, codigoPostal, numIntentosEntrega, dninif, idEstadoEnvio, idCliente
}
console.table(contenido)
this.conexion.actualizarEnvio(contenido).subscribe(xx => this.envioactual = xx);
}
}
This my conexion service
actualizarEnvio(conexion : Envio)
{
const path = `${this.api}/actualizarEnvio/${conexion.idEnvio}`;
return this.http.put<Envio>(path, conexion);
}
This is the interface
export interface Envio
{
idEnvio : number;
nombreDestinatario: string;
dninif: string;
codigoPostal: string;
direccionCompleta:string;
idEstadoEnvio: string;
numIntentosEntrega: number;
idCliente: string;
}
And the relationship on database
[1]: https://i.stack.imgur.com/CodiV.png

Problem with special character in controller in Laravel

I am trying to save multiple checkbox values, and its value attributes contain special characters, such as "ç," "ã," and so on. But when I get into my controller and return the $request object, I see that the special characters are not being formatted in utf-8. How can I solve this, please?
HTML
<div class="form-check">
<input class="form-check-input" name="servicos[]" type="checkbox"
value="Substituição de piso nos banheiros" id="servicos1">
<label class="form-check-label" for="flexRadioDefault1">
Substituição de piso nos banheiros
</label>
</div>
<div class="form-check">
<input class="form-check-input" name="servicos[]" type="checkbox"
value="Instalação de piso na sala e dormitórios" id="servicos2">
<label class="form-check-label" for="flexRadioDefault1">
Instalação de piso na sala e dormitórios
</label>
</div>
<div class="form-check">
<input class="form-check-input" name="servicos[]" type="checkbox"
value="Substituição de piso na cozinha" id="servicos3">
<label class="form-check-label" for="flexRadioDefault1">
Substituição de piso na cozinha
</label>
</div>
Controller
return $request->servicos;

Angular insert data in mysql

I am unable to insert de data into mysql using angular. If i want to fetch data in mysql it works ok, but this doesn't work.
I can't see the error. Can you help me?
this is my html form:
<form #suscribir="ngForm">
<div class="modal-body bodycolabora">
<label class="labelmodal">Recibe nuestros correos para estar al tanto de los últimos post y recursos subidos.</label>
<div class="md-form mb-2">
<label class="labelmodal">Tu nombre*</label>
<input class="form-control" type="text" name="nombre" class="input" placeholder="Tu nombre" [(ngModel)]="datos.nombre" required minlength="3" #nameInput="ngModel">
</div>
<div *ngIf="nameInput.invalid && (nameInput.dirty || nameInput.touched)"
class="alert alert-danger">
<div *ngIf="nameInput.errors.required">
Escribe tu nombre.
</div>
<div *ngIf="nameInput.errors.minlength">
Name must be at least 4 characters long.
</div>
</div>
<div class="md-form mb-2">
<label class="labelmodal">Email*</label>
<input class="form-control" type="email" name="email" class="input" placeholder="Tu email" [(ngModel)]="datos.email" required email #emailInput="ngModel">
</div>
<div *ngIf="emailInput.invalid && (emailInput.dirty || emailInput.touched)"
class="alert alert-danger">
<div *ngIf="emailInput.errors.required">
Escribe tu email.
</div>
</div>
<!--Privacidad-->
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="aceptopolitica" name="privacidad" value="acepto" ngModel required #privacidadInput="ngModel">
<label class="labelmodal" class="form-check-label" for="infantil" name="etapa" >Acepto la Política de privacidad</label>
</div>
<div *ngIf="privacidadInput.invalid && (privacidadInput.dirty || privacidadInput.touched)"
class="alert alert-danger">
<div *ngIf="privacidadInput.errors.required">
Acepta la política de privacidad
</div>
</div>
</div>
<div class="modal-footer footercolabora d-flex justify-content-center">
<button (click)="suscriptores()" value="Nuevo suscriptor" type="submit" name="submit" id="submit" class="btn btncolabora" [disabled]="suscribir.invalid">Enviar →</button>
</div>
</form>
In my component.ts i have:
datos={
nombre:null,
email:null
}
constructor(private articulosServicio: ServicioService) {
}
suscriptores() {
this.articulosServicio.suscriptores(this.datos).subscribe(datos => {
if (datos['resultado']=='OK') {
alert(datos['mensaje']);
}
});
In the service.ts:
url='http://xxxxxxxxxxx/'; //
constructor(private http: HttpClient) { }
suscriptores(datos) {
return this.http.post(`${this.url}suscriptores.php`, JSON.stringify(datos));
}
and finally the file.php,
<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Content-Type: application/json');
$json = file_get_contents('php://input');
$params = json_decode($json);
require("conexion.php");
$con=retornarConexion();
$email = mysqli_real_escape_string($con, $params->email);
$nombre = mysqli_real_escape_string($con, $params->nombre);
$query= 'INSERT INTO newsletter(email, nombre) VALUES ("' . $email . '","'. $nombre .'")';
if(mysqli_query($con, $query))
{
class Result {}
$response = new Result();
$response->resultado = 'OK';
$response->mensaje = 'datos grabados';
}
else
{
class Result {}
$response = new Result();
$response->resultado = 'OK';
$response->mensaje = 'datos grabados';
}
header('Content-Type: application/json');
echo json_encode($response);
?>
Sorry for all the code but i think you might need id to see the error

Dynamic row is not saved in database with Laravel Controller

I have a form in my view which asks for education qualification of students(I have provided the code below). I want the user (in my case a Student) while filling up the form should be able to dynamically add his/her subjects, total marks and marks obtained in the database table. All thing works fine when i add only one subject. But the problem comes when i try to add multiple subjects. Looking forward for a solution from you people..
This is the form in my view :
<form action="/edu_details" method="post">
#csrf
<div class="jumbotron">
<div class="form-row">
<div class="form-group col-md-12">
<label for="institution">Institution Last Attended</label>
<input type="text" class="form-control" name="institution" id="institution" value="{{old('institution')}}">
#if ($errors->has('institution'))
<div class="error" style="color:red;">{{ $errors->first('institution') }}</div>
#endif
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<label for="yop">Year of Passing</label>
<input type="text" class="form-control" name="yop" id="yop" value="{{old('yop')}}">
#if ($errors->has('yop'))
<div class="error" style="color:red;">{{ $errors->first('yop') }}</div>
#endif
</div>
<div class="form-group col-md-8">
<label for="board">Board</label>
<div class="col-sm-12">
<select name="board" id="board" class="form-control">
<option hidden disabled selected value> -- Select an option -- </option>
<option>SEBA</option>
<option>CBSE</option>
<option>Other</option>
</select>
</div>
#if ($errors->has('board'))
<div class="error" style="color:red;">{{ $errors->first('board') }}</div>
#endif
</div>
</div>
</div>
<div class="jumbotron">
<table class="table table-bordered">
<thead>
<tr>
<th>Name of the Subject</th>
<th>Total Marks</th>
<th>Marks Obtained</th>
<th>+</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" name="subj[]" class="form-control">
#if ($errors->has('subj'))
<div class="error" style="color:red;">{{ $errors->first('subj') }}</div>
#endif
</td>
<td>
<input type="text" name="totl" class="form-control">
#if ($errors->has('totl'))
<div class="error" style="color:red;">{{ $errors->first('totl') }}</div>
#endif
</td>
<td>
<input type="text" name="obtn" class="form-control">
#if ($errors->has('obtn'))
<div class="error" style="color:red;">{{ $errors->first('obtn') }}</div>
#endif
</td>
<td>
-
</td>
</tr>
</tbody>
</table>
</div>
<div class="jumbotron">
<div class="form-row">
<label for="sub_group">Group of subjects the applicant wishes to opt :</label>
<div class="form-group col-md-12">
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="sub_group" id="sub_group" value="Major">
<label class="form-check-label" for="sub_group">Major</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="sub_group" id="sub_group" value="General">
<label class="form-check-label" for="sub_group">General</label>
</div>
</div>
#if ($errors->has('sub_group'))
<div class="error" style="color:red;">{{ $errors->first('sub_group') }}</div>
#endif
</div>
<div class="form-row">
<div class="col-sm-4">
<label for="pref1">1st Preference</label>
<select name="pref1" id="pref1" class="form-control">
<option hidden disabled selected value> -- Select an option -- </option>
<option>Sub1</option>
<option>Sub2</option>
<option>Sub3</option>
</select>
#if ($errors->has('pref1'))
<div class="error" style="color:red;">{{ $errors->first('pref1') }}</div>
#endif
</div>
<div class="form-group col-md-8">
<label for="prefgroup1"> </label>
<div class="col-sm-12">
<select name="prefgroup1" id="prefgroup1" class="form-control">
<option hidden disabled selected value> -- Select an option -- </option>
<option>Sub1</option>
<option>Sub2</option>
<option>Sub3</option>
</select>
#if ($errors->has('prefgroup1'))
<div class="error" style="color:red;">{{ $errors->first('prefgroup1') }}</div>
#endif
</div>
</div>
</div>
<div class="form-row">
<div class="col-sm-4">
<label for="pref2">2nd Preference</label>
<select name="pref2" id="pref2" class="form-control">
<option hidden disabled selected value> -- Select an option -- </option>
<option>Sub1</option>
<option>Sub2</option>
<option>Sub3</option>
</select>
#if ($errors->has('pref2'))
<div class="error" style="color:red;">{{ $errors->first('pref2') }}</div>
#endif
</div>
<div class="form-group col-md-8">
<label for="prefgroup2"> </label>
<div class="col-sm-12">
<select name="prefgroup2" id="prefgroup2" class="form-control">
<option hidden disabled selected value> -- Select an option -- </option>
<option>Sub1</option>
<option>Sub2</option>
<option>Sub3</option>
</select>
</div>
#if ($errors->has('prefgroup2'))
<div class="error" style="color:red;">{{ $errors->first('prefgroup2') }}</div>
#endif
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-block">Submit Data</button>
</form>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(".addRow").on('click', function(){
addRow();
return false;
});
function addRow(){
var tr = '<tr>'+
'<td><input type="text" name="subj[]" class="form-control">#if ($errors->has('subj'))
<div class="error" style="color:red;">{{ $errors->first('subj') }}</div>
#endif </td>'+
'<td><input type="text" name="totl" class="form-control"></td>'+
'<td><input type="text" name="obtn" class="form-control"></td>'+
'<td>-</td>'+
'</tr>';
$('tbody').append(tr);
$('tbody').on('click','.delRow',function(){
$(this).parent().parent().remove();
return false;
});
}
</script>
This is my controller's save method :
public function store(Request $request)
{
$validatedData = $request->validate([
'institution' => 'required|max:255',
'yop' => 'required',
'board' => 'required|max:255',
'subj' => 'required|max:255',
'totl' => 'required',
'obtn' => 'required',
'sub_group' => 'required|max:255',
'pref1' => 'required|max:255',
'prefgroup1' => 'required|max:255',
'pref2' => 'required|max:255',
'prefgroup2' => 'required|max:255',
]);
//Insert student data if validated
$edudetail = new EduDetail();
$edudetail->user_id = Auth::user()->id;
//$edudetail->user_id = DB::table('pictures')->where('user_id', $user_id)->value('id');
$edudetail->institution = $request->input('institution');
$edudetail->yop = $request->input('yop');
$edudetail->board = $request->input('board');
foreach($request->get('subj') as $subj) {
$edudetail->subj[] = $subj;
$edudetail->save();
}
$edudetail->totl = $request->input('totl');
$edudetail->obtn = $request->input('obtn');
$edudetail->sub_group = $request->input('sub_group');
$edudetail->pref1 = $request->input('pref1');
$edudetail->prefgroup1 = $request->input('prefgroup1');
$edudetail->pref2 = $request->input('pref2');
$edudetail->prefgroup2 = $request->input('prefgroup2');
$edudetail->save();
return redirect('/student_dox_upload')->with('success','Education Details saved.');
}
I have tried to see if the values are passed as arrays in case of the subject field using print_r method.. And the values are seen in arrays... that's working fine.. but when i go to save only the last record of the dynamic row gets added.. For example if i add 3 subjects English, Maths and Science.. I want all 3 subjects to be added in a column but only Science is getting added.. Any help is appreciated..
Like the bottom, make a fillable for the input values ​​inside the model
$fillable=['institution',...];
Rules in the file in the request on the path
app \ Http \ Request
Define in a file
And then save the data in the form below
public function store(NewServiceRequest $request,Variable $variable,Variable $variable){
$variable->fill($request->only($variable->getFillable()));
$variable->save();
$variable->variable()->save($variable);
.
.
.
}
I did exactly what you said and it worked for the subjects field... But when I tried to implement your solution with the totl field and obtn field i got an error..
I tried this :
$edudetail = new EduDetail();
$edudetail->user_id = Auth::user()->id;
//$edudetail->user_id = DB::table('pictures')->where('user_id', $user_id)->value('id');
$edudetail->institution = $request->input('institution');
$edudetail->yop = $request->input('yop');
$edudetail->board = $request->input('board');
$edudetail->subj = json_encode($request->get('subj'));
$edudetail->totl = json_encode($request->get('totl'));
$edudetail->obtn = json_encode($request->get('obtn'));
$edudetail->sub_group = $request->input('sub_group');
$edudetail->pref1 = $request->input('pref1');
$edudetail->prefgroup1 = $request->input('prefgroup1');
$edudetail->pref2 = $request->input('pref2');
$edudetail->prefgroup2 = $request->input('prefgroup2');
$edudetail->save();
I got this error :
Illuminate \ Database \ QueryException (22007)
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: '["100","100","100","100"]' for column cas_db.edu_details.totl at row 1 (SQL: insert into edu_details (user_id, institution, yop, board, subj, totl, obtn, sub_group, pref1, prefgroup1, pref2, prefgroup2, updated_at, created_at) values (1, Little Flower School, 2004, CBSE, ["Science","Maths","Computer","English"], ["100","100","100","100"], ["72","76","80","78"], General, Sub2, Sub1, Sub3, Sub2, 2019-07-28 11:21:24, 2019-07-28 11:21:24))

No refresh on submit

I've got a site with a form.
The value of the input should be a specific value. This works:
$('button').on('click', function () {
var val1 = $("#teller").val();
var val2 = $("#noemer").val();
if (val1 == 3 && val2 == 10)
alert("Goed gedaan! je hebt de vraag goed beantwoord. Je kunt verder met je avontuur!");
else
alert("Helaas... Dit is niet het goede antwoord. Probeer het nog eens!");
});
But when I submit the page will refresh, change my url and refresh the page so the page starts at the beginning again... This is the site: http://stilld.nl/brrreuk/
I don't want this to happen. I want the code to check if the value's given are correct, but then I want the site to stay where it is.
Hope you can help.
this is the html:
<form id="form_1">
<fieldset>
<p>
<input type="text" class="input_required" id="teller" name="teller" maxlength="2" class="valid" aria-invalid="false" onkeydown="return isNumber(event);" placeholder="?" onfocus="this.placeholder = ''" onblur="this.placeholder = '?'">
<label for="teller"></label>
</p>
<hr noshade size=3>
<p>
<input type="text" class="input_required" id="noemer" name="noemer" maxlength="2" class="valid" aria-invalid="false" onkeydown="return isNumber(event);" placeholder="?" onfocus="this.placeholder = ''" onblur="this.placeholder = '?'">
<label for="noemer"></label>
</p>
<p>
<button class="submit" type="submit" value="controleer">Controleer</button>
</p>
</fieldset>
</form>
Here you go. Simply change the submit to a button.
The JavaScript:
$('button').on('click', function(){
var val1 = $("#teller").val();
var val2 = $("#noemer").val();
if(val1 == 3 && val2 == 10)
alert("Goed gedaan! je hebt de vraag goed beantwoord. Je kunt verder met je avontuur!");
else
alert("Helaas... Dit is niet het goede antwoord. Probeer het nog eens!");
});
And the HTML
<p>
<input type="text" class="input_required" id="teller" name="teller" maxlength="2" class="valid" aria-invalid="false" onkeydown="return isNumber(event);" placeholder="?" onfocus="this.placeholder = ''" onblur="this.placeholder = '?'">
<label for="teller"> </label>
</p>
<hr noshade size=3>
<p>
<input type="text" class="input_required" id="noemer" name="noemer" maxlength="2" class="valid" aria-invalid="false" onkeydown="return isNumber(event);" placeholder="?" onfocus="this.placeholder = ''" onblur="this.placeholder = '?'">
<label for="noemer"> </label>
</p>
<p>
<button type="button" value="controleer"> Controleer </button>
</p>
List to the form's submit event instead of the button's click event:
$('form').on('submit', function(e) {
e.preventDefault();
// do stuff
// $(this).trigger('submit') if everything's ok
});
NOTE: The e.preventDefault(); line is important!