I have a basic question but i can't find the solution .
how can i force my user to check the box : accept the condition ? (j'acceptes les conditions d'utilisations = i agree terms & conditions )
here is a pictures of my form :
here is my HTML:
<section id="formDom">
<form class="column g-3 needs-validation" novalidate>
<div class="col-md-4">
<label for="validationCustom01" class="form-label">Nom</label>
<input type="text" class="form-control" placeholder="Dupont" id="firstName" required>
<div class="valid-feedback">
Ok
</div>
</div>
<div class="col-md-4">
<label for="validationCustom01" class="form-label">prénom</label>
<input type="text" class="form-control" placeholder="Jean" id="lastName" required>
<div class="valid-feedback">
Ok
</div>
</div>
<div class="col-md-4">
<label for="validationCustomUsername" class="form-label">Adresse mail</label>
<div class="input-group has-validation">
<span class="input-group-text" id="inputGroupPrepend">#</span>
<input type="email" class="form-control" id="email" aria-describedby="inputGroupPrepend"
placeholder="jeandupont#gmail.com" required>
<div class="invalid-feedback">
Adresse mail requise
</div>
</div>
</div>
<div class="col-md-4">
<label for="validationCustom01" class="form-label">Ville</label>
<input type="text" class="form-control" placeholder="Paris" id="city" required>
<div class="valid-feedback">
Ok
</div>
</div>
<div class="col-md-4">
<label for="validationCustom03" class="form-label">Adresse</label>
<input type="text" class="form-control" placeholder="1 rue de Paris" id="adress" required>
<div class="invalid-feedback">
adresse réquise
</div>
</div>
<div class="col-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
<label class="form-check-label" for="invalidCheck">
J'accepte les conditions d'utilisations
</label>
<div class="invalid-feedback">
Vous devez accepteer les conditions d'utilisations
</div>
</div>
</div>
<div class="col-md-4">
<button id="buyBtn" class="btn btn-primary basket-btn" type="submit">Acheter</button>
</div>
</form>
</section>
Actually the user is forced to fill the form but he can submit without check the box ( accept condition )
Here is the JS :
function validForm() {
const form = document.querySelector('.needs-validation');
form.addEventListener('submit', function (event) {
event.preventDefault();
event.stopPropagation();
cameraIds = getBasket().map(item => { return item.id });
const contact = {
email: document.getElementById("email").value,
firstName: document.getElementById("firstName").value,
lastName: document.getElementById("lastName").value,
city: document.getElementById("city").value,
address: document.getElementById("adress").value,
}
createOrder(contact, cameraIds, (order, error) => {
if (error) {
alert('Merci de remplir le formulaire');
} else {
localStorage.clear();
location.assign(`confirmation.html?id=${order.orderId}`)
}
form.classList.add('was-validated');
})
})
}
validForm();
PS : i'm using BOOTSTRAP but i think you got it ^^
if(document.getElementById('invalidCheck').checked==true)
//you'r accepted the terms
else
//you should accept the terms
You can check if a checkbox is checked or not by testing the checked property of the input element:
var isChecked = document.querySelector('input[type="checkbox"]').checked;
if(!isChecked) {
alert("You must accept the terms before proceeding");
}
In your case, it will be:
var isChecked = document.querySelector('.needs-validation .form-check-input').checked;
You can check for document.getElementById("").checked
Related
Im working with forms so need to customize validations with "setCustomValidity" function, the problem comes when i work with alerts and validations in the same.
The button that i use to send my data form got type="submit" when i use that kind my form is making validations correctly but that type makes a refresh so the alert never shows up.
If i switch the type to type="button" then makes the opposite. Validations are not working and alerts finally shows up.
Here is some of the form´s side code:
<div class="modal-dialog">
<div class="modal-content">
<div class="col-12 user-img">
<img src="../../images/nuevoConcesionario.png" alt="">
</div>
<span id="switching1" class="d-none">
<center>
<div class="alert alert-danger" role="alert" id="mensajeError" value="AA">
</div>
</center>
</span>
<form class="formu">
<div class="row">
<div class="form-group col-md-6">
<label for="nombre" class="col-form-label">Nombre Concesionario(*)</label>
<input type="text" class="form-control" id="nomConcesionario" placeholder="Nombre Concesionario" required>
</div>
<div class="form-group col-md-6">
<label for="Nif" class="col-form-label">NIF(*)</label>
<input type="text" class="form-control" id="nifConcesionario" placeholder="Ejemplo NIF: A58818501" required>
</div>
</div>
<div class="row">
<div class="form-group col-md-6" >
<label for="ciudad" class="col-form-label">Ciudad(*)</label>
<input type="text" class="form-control" id="nomCiudad" placeholder="Ciudad" required>
</div>
<div class="form-group col-md-6">
<label for="cp" class="col-form-label">Codigo Postal</label>
<input type="text" id="cpConcesionario" placeholder="Codigo Postal" class="form-control">
</div>
</div>
<div class="row">
<div class="form-group col-md-6" >
<label for="ciudad" class="col-form-label">Telefono Contacto</label>
<input type="tel" class="form-control" id="tlf" placeholder="Telefono Contacto">
</div>
<div class="form-group col-md-6">
<label for="nom_admin" class="col-form-label">Nombre Administrador(*)</label>
<input type="text" id="nomAdministrador" placeholder="Nombre Administrador" class="form-control" required>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="email" class="col-form-label">Email(*)</label>
<input type="email" id="emailConcesionario" placeholder="email" class="form-control" required>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="nom_admin" class="col-form-label">Dirección(*)</label>
<input type="text" id="direccion" placeholder="direccion" class="form-control" required>
</div>
</div>
<div class="row">
<div style="width: 100%; margin: 0 25% 0 25%">
<button type="button" id="bEnviar" class="btn btn-primary" onclick="altaConcesionario();">Dar de alta concesionario</button>
</div>
</div>
</form>
Here is altaConcesionario validation´s function:
function altaConcesionario() {
var nomConcesionario = document.getElementById('nomConcesionario');
var nifConcesionario = document.getElementById('nifConcesionario');
var nomCiudad = document.getElementById('nomCiudad');
var nomAdministrador = document.getElementById('nomAdministrador');
var cpConcesionario = document.getElementById('cpConcesionario');
var telefono = document.getElementById('tlf');
var direccion = document.getElementById('direccion');
var emailConcesionario = document.getElementById('emailConcesionario');
// TODO unificar este mismo patron
var nomConcesionarioPatt = /[A-Za-z0-9]{4,60}/;
var nomCiudadPatt = /[A-Za-z0-9]{4,60}/;
var nomAdminPatt = /[A-Za-z0-9]{4,60}/;
var addrPatt = /[A-Za-z0-9]{4,60}/;
var emailConcesionarioPatt = /^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;
var elNif = checkNif(nifConcesionario.value);
var validate = true;
// Nombre concesionario
if (nomConcesionario.value) {
nomConcesionario.setCustomValidity("");
if (!nomConcesionarioPatt.test(nomConcesionario.value)) {
mostrarAlertaValidacion("Error en el ingreso. min[4] caracteres");
nomConcesionario.setCustomValidity("Error en el ingreso. min[4] caracteres");
validate = false;
}
} else {
nomConcesionario.setCustomValidity("Por favor, rellene campo 'nombre concesionario'");
mostrarAlertaValidacion("Por favor, rellene campo 'nombre concesionario'");
validate = false;
}
// Nif concesionario
if (nifConcesionario.value) {
nifConcesionario.setCustomValidity("");
if (!elNif) {
nifConcesionario
.setCustomValidity("El nif introducido no es correcto");
validate = false;
}
} else {
nifConcesionario
.setCustomValidity("Por favor, rellene campo 'NIF concesionario'");
validate = false;
}
// Nombre ciudad
if (nomCiudad.value) {
nomCiudad.setCustomValidity("");
if (!nomCiudadPatt.test(nomCiudad.value)) {
nomCiudad
.setCustomValidity("Error en el ingreso. min[4] caracteres");
validate = false;
}
} else {
nomCiudad.setCustomValidity("Por favor, rellene campo 'nombre ciudad'");
validate = false;
}
// Nombre administrador
if (nomAdministrador.value) {
nomAdministrador.setCustomValidity("");
if (!nomAdminPatt.test(nomAdministrador.value)) {
nomAdministrador
.setCustomValidity("Error en el ingreso. min[4] caracteres");
validate = false;
}
} else {
nomAdministrador
.setCustomValidity("Por favor, rellene campo 'nombre administrador'");
validate = false;
}
if (direccion.value) {
direccion.setCustomValidity("");
if (!addrPatt.test(direccion.value)) {
direccion
.setCustomValidity("Error en el ingreso. min[4] caracteres");
validate = false;
}
} else {
direccion.setCustomValidity("Por favor, rellene campo 'direccion'");
validate = false;
}
// Email concesionario
if (emailConcesionario.value) {
emailConcesionario.setCustomValidity("");
if (!emailConcesionarioPatt.test(emailConcesionario.value)) {
emailConcesionario
.setCustomValidity("El email introducido no es correcto. mail#dominio.com");
validate = false;
}
} else {
emailConcesionario
.setCustomValidity("Por favor, rellene campo 'email colaborador'");
validate = false;
}
// TODO falta validacion email
// TODO poner las rewdirecciones en su sitio
// Si estan todos los campos rellenos entra
if (validate) {
// POPUP
// SI TRUE
$
.ajax({
type : "POST",
url : '/proyecto/Api',
data : {
action : 'addConcesionario',
auth_token : auth_token,
usuario_sesion : usuario,
nomConcesionario : nomConcesionario.value,
nifConcesionario : nifConcesionario.value,
nomCiudad : nomCiudad.value,
nomAdministrador : nomAdministrador.value,
cpConcesionario : cpConcesionario.value,
telefono : telefono.value,
direccion : direccion.value,
email : emailConcesionario.value
},
success : function(response) {
alert("EXITO");
window.location.href = "/proyecto/administracion/administracion.jsp";
},
error : function(result) {
alert("ERROR");
window.location.href = "/proyecto/administracion/administracion.jsp";
}
});
}
so i would like to know if there is any reasonable way to make both works together as i need to give information to the final user and is really important for me both of functions.
Thanks in advance,
This happened because you need to prevent form submitting event.preventDefault(). Take a look at example below
const form = document.querySelector('#myForm');
form.addEventListener('submit', ev => {
ev.preventDefault();
//Your code here (validation, http etc)
console.log('Prevented');
})
<form id="myForm">
<div class="row">
<div class="form-group col-md-6">
<label for="nombre" class="col-form-label">Nombre Concesionario(*)</label>
<input type="text" class="form-control" id="nomConcesionario" placeholder="Nombre Concesionario" required>
</div>
<div class="form-group col-md-6">
<label for="Nif" class="col-form-label">NIF(*)</label>
<input type="text" class="form-control" id="nifConcesionario" placeholder="Ejemplo NIF: A58818501" required>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="ciudad" class="col-form-label">Ciudad(*)</label>
<input type="text" class="form-control" id="nomCiudad" placeholder="Ciudad" required>
</div>
<div class="form-group col-md-6">
<label for="cp" class="col-form-label">Codigo Postal</label>
<input type="text" id="cpConcesionario" placeholder="Codigo Postal" class="form-control">
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="ciudad" class="col-form-label">Telefono Contacto</label>
<input type="tel" class="form-control" id="tlf" placeholder="Telefono Contacto">
</div>
<div class="form-group col-md-6">
<label for="nom_admin" class="col-form-label">Nombre Administrador(*)</label>
<input type="text" id="nomAdministrador" placeholder="Nombre Administrador" class="form-control" required>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="email" class="col-form-label">Email(*)</label>
<input type="email" id="emailConcesionario" placeholder="email" class="form-control" required>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="nom_admin" class="col-form-label">Dirección(*)</label>
<input type="text" id="direccion" placeholder="direccion" class="form-control" required>
</div>
</div>
<div class="row">
<div style="width: 100%; margin: 0 25% 0 25%">
<button type="submit" class="btn btn-primary">Dar de alta concesionario</button>
</div>
</div>
</form>
I need to hide a div for aditional coments if the input file is empty.
I don't mind if it's done with Jquery or plain Javascript.
I've used JQuery, I know that it's been called correctly because my alert pops up, but my function does not hide the div with ID: #instrucciones-adicionales and all its contents.
HTML:
<script>
alert( "Animation complete." );
$(function () {
$("input:file").change(function () {
var fileName = $(this).val();
if (filename != "") {
$("#instrucciones-adicionales").hide();
} //show the button
});
});
</script>
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="csrfmiddlewaretoken" value="Ka5bun8eHCmm5pReR7M9JCOxP8YxVq1sBfi79yqnXFEFWEksDE8WSDfgiYxf2KDb">
<div class="form-group">
<div id="div_id_imagenes" class="form-group">
<label for="id_imagenes" class="col-form-label requiredField">
Imagenes<span class="asteriskField">*</span>
</label>
<div class="">
<input type="file" name="imagenes" class="clearablefileinput" required id="id_imagenes">
</div>
</div>
<div id="instrucciones-adicionales">
<p class="bold-font"> Instrucciones adicionales (opcional):</p>
<div id="div_id_instrucciones" class="form-group">
<label for="id_instrucciones" class="col-form-label requiredField">
Instrucciones<span class="asteriskField">*</span>
</label>
<div class="">
<textarea name="instrucciones" cols="40" rows="10" class="textarea form-control" required id="id_instrucciones">
</textarea>
</div>
</div>
</div>
</div>
</br>
</br>
<p>O, sáltate este paso y envía tu arte por correo electrónico</p>
<button type="submit" class="btn btn-naranja text-white btn-block">Continuar
</button>
You had a typo (variables are case sensitive - fileName !== filename).
I added the show part:
alert( "Animation complete." );
$(function () {
$("input:file").change(function () {
var fileName = $(this).val();
if (fileName != "") {
$("#instrucciones-adicionales").hide();
} else {
$("#instrucciones-adicionales").show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main role="main">
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="csrfmiddlewaretoken" value="Ka5bun8eHCmm5pReR7M9JCOxP8YxVq1sBfi79yqnXFEFWEksDE8WSDfgiYxf2KDb">
<div class="form-group">
<div id="div_id_imagenes" class="form-group">
<label for="id_imagenes" class="col-form-label requiredField">
Imagenes<span class="asteriskField">*</span>
</label>
<div class="">
<input type="file" name="imagenes" class="clearablefileinput" required id="id_imagenes">
</div>
</div>
<div id="instrucciones-adicionales" style="display: none">
<p class="bold-font"> Instrucciones adicionales (opcional):</p>
<div id="div_id_instrucciones" class="form-group">
<label for="id_instrucciones" class="col-form-label requiredField">
Instrucciones<span class="asteriskField">*</span>
</label>
<div class="">
<textarea name="instrucciones" cols="40" rows="10" class="textarea form-control" required id="id_instrucciones">
</textarea>
</div>
</div>
</div>
</div>
</br>
</br>
<p>O, sáltate este paso y envía tu arte por correo electrónico</p>
<button type="submit" class="btn btn-naranja text-white btn-block">Continuar
</button>
</form>
</main>
could you please tell me how to show validation message on button click ? here is my code
https://stackblitz.com/edit/angular-ugdbvg?file=src/app/app.component.html
I want to show required error message when user press submit button.
<form novalidate [formGroup]="searchForm" class="calform">
<section class="col-sm-6 bg-white pl-20 pr-20">
<div class="form-group col-sm-4 pl-0 error">
<label class="field-title mb-5">name<span class="color-red fontWt"> *</span></label>
<input type="text" placeholder="Enter name" formControlName="name">
<p class="message" [hidden]="searchForm.get('name')">Required</p>
</div>
<div class="form-group col-sm-4 pl-0 error">
<label class="field-title mb-5">last name <span class="color-red fontWt"> *</span></label>
<input type="text" placeholder="Enter last name" formControlName="lastName">
<p class="message" [hidden]="searchForm.get('lastName')">Required</p>
</div>
<button (click)="submitHandler()">submit</button>
</section>
</form>
js
this.searchForm = this.fb.group({
name: ['', Validators.required],
lastName: ['', Validators.required]
});
Add the following line to check:
<span class="error" *ngIf="!!searchForm.controls.name.errors.required && (!!searchForm.controls.name.dirty || !!searchForm.controls.name.touched)">
Name is required.
</span>
<span class="error" *ngIf="!!searchForm.controls.lastName.errors.required && (!!searchForm.controls.lastName.dirty || !!searchForm.controls.name.touched)">
lastName is required.
</span>
in your ts file:
submitHandler() {
if(this.searchForm.valid) {
// Logic
}
}
https://stackblitz.com/edit/angular-utvw23
You need to use *ngIf. Updated Stackblitz code . https://stackblitz.com/edit/angular-fzyrji
Try like this:
Use [hidden] or *ngIf
DEMO
<div class="form-group col-sm-4 pl-0 error">
<label class="field-title mb-5">name<span class="color-red fontWt"> *</span></label> {{show}}
<input type="text" placeholder="Enter name" formControlName="name"> {{searchForm.get('name').invalid}}
<p class="message" [hidden]="!(show && searchForm.get('name').invalid)">Required</p>
</div>
<div class="form-group col-sm-4 pl-0 error">
<label class="field-title mb-5">last name <span class="color-red fontWt"> *</span></label>
<input type="text" placeholder="Enter last name" formControlName="lastName">
<p class="message" [hidden]="!(show && searchForm.get('lastName').invalid)">Required</p>
</div>
<button (click)="show = true ; submitHandler();">submit</button>
</section>
</form>
I have a registration form that I would like to have multiple field validation. What I mean by this is if more than one field is not filled in it will be highlighted red. I have some code already written but instead of highlighting the field not filled in, it's highlighting all of them. I realise it is quite long winded but I'm fairly new to this. My JS code is as follows:
`function formCheck() {
var val = document.getElementById("fillMeIn").value;
var val = document.getElementById("fillMeIn2").value;
var val = document.getElementById("fillMeIn3").value;
var val = document.getElementById("fillMeIn4").value;
var val = document.getElementById("fillMeIn5").value;
var val = document.getElementById("fillMeIn6").value;
var val = document.getElementById("fillMeIn7").value;
if (val == "") {
alert("Please fill in the missing fields");
document.getElementById("fillMeIn").style.borderColor = "red";
document.getElementById("fillMeIn2").style.borderColor = "red";
document.getElementById("fillMeIn3").style.borderColor = "red";
document.getElementById("fillMeIn4").style.borderColor = "red";
document.getElementById("fillMeIn5").style.borderColor = "red";
document.getElementById("fillMeIn6").style.borderColor = "red";
document.getElementById("fillMeIn7").style.borderColor = "red";
return false;
}
else {
document.getElementById("fillMeIn").style.borderColor = "green";
document.getElementById("fillMeIn2").style.borderColor = "green";
document.getElementById("fillMeIn3").style.borderColor = "green";
document.getElementById("fillMeIn4").style.borderColor = "green";
document.getElementById("fillMeIn5").style.borderColor = "green";
document.getElementById("fillMeIn6").style.borderColor = "green";
document.getElementById("fillMeIn7").style.borderColor = "green";
}
}`
My HTML is as follows:
'<form id="mbrForm" onsubmit="return formCheck();" action="thanks.html" method="post">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
FIRST NAME:
<input id="fillMeIn" type="text" class="form-control" placeholder="First Name" >
</div>
<div class="col-md-4 vertical-gap">
LAST NAME:
<input id="fillMeIn2" type="text" class="form-control" placeholder="Last Name" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8 vertical-gap">
ADDRESS:
<input id="fillMeIn3" type="text" class="form-control vertical-gap" placeholder="First Line" >
<input id="fillMeIn4" type="text" class="form-control vertical-gap" placeholder="Second Line" >
<input id="fillMeIn5" type="text" class="form-control vertical-gap" placeholder="Town/City" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
POST CODE:
<input id="fillMeIn6" type="text" class="form-control vertical-gap" placeholder="Postcode" >
</div>
<div class="col-md-4 vertical-gap">
PHONE No:
<input type="number" class="form-control vertical-gap" placeholder="Tel no">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
EMAIL ADDRESS:
<input id="fillMeIn7" type="email" class="form-control vertical-gap" placeholder="Email address" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row vertical-gap">
<div class="col-md-2"></div>
<div class="col-md-8">
DISCIPLINE:
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Cross Country"> CROSS COUNTRY
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Enduro"> ENDURO
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Downhill"> DOWNHILL
</label>
</div>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-10">
<!--<button type="button" input type="hidden" class="btn btn-success" name="redirect" value="thanks.html">SUBMIT</button>-->
<input type="submit" value="SUBMIT" class="btn btn-success btn-lg">
</div>
<div class="col-md-2"></div>
</div>
</form>'
Thanks!
You could have the ids in an Array, iterate through its values, and execute the repeatable code in a function that groups all the logic inside.
example :
["fillMeIn1", "fillMeIn2", "fillMeIn3", "fillMeIn4"].each(function(id){
// do things with id
})
Why not use the html "required" property instead?
If you want to do this with JS, you should give each variable a different name. In the code you posted you are continuously overwriting the same variable, and then, it evaluates val (which ended up being assigned to the (fill me7 value) to "", and if true, setting all the borders to red.
Set different variables, push the input values into an array when submit is triggered and loop through them if variables[i]==0, set getElementId(switch case[i] or another array with the name of the inputs[i]).bordercolor to red.
AGAIN, this sound VERY INEFFICIENT and I am not sure at all it would work. My guess is that it would take A LOT of time, and probably get timed out (except you are using some asych/try-catch kind of JS).
I would simply go for an HTML required property and then override the "required" property in CSS to make it look as you intend to. Simpler, easy and clean.
The main issue in your code is that you override the variable val each time you wrote var val = ....
Keeping your own your logic, you could write something like that.
var formModule = (function () {
var $fields = [
document.getElementById('fillMeIn'),
document.getElementById('fillMeIn2'),
document.getElementById('fillMeIn3'),
document.getElementById('fillMeIn4'),
document.getElementById('fillMeIn5'),
document.getElementById('fillMeIn6'),
document.getElementById('fillMeIn7')
];
function markInvalid($field) {
$field.style.borderColor = 'red';
}
function markValid($field) {
$field.style.borderColor = 'green';
}
return {
check: function () {
var isValid = true;
$fields.forEach(function ($f) {
if ($f.value === '') {
if (isValid) alert('Please fill in the missing fields');
isValid = false;
markInvalid($f);
}
else markValid($f);
});
return isValid;
}
};
})();
There are some extra concepts in this example which may be useful:
Working with the DOM is really slow, that's why you should
put your elements in a variable once for all and not everytime you
click on the submit button.
In my example i wrap the code with var formModule = (function () {...})();.
It's called module pattern. The goal is to prevent variables to leak in the rest of the application.
A better solution could be this one using the 'power' of html form validation:
HTML:
<form id="mbrForm" action="thanks.html" method="post">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
FIRST NAME:
<input id="fillMeIn" type="text" required class="form-control" placeholder="First Name">
</div>
<div class="col-md-4 vertical-gap">
LAST NAME:
<input id="fillMeIn2" type="text" required class="form-control" placeholder="Last Name">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8 vertical-gap">
ADDRESS:
<input id="fillMeIn3" type="text" required class="form-control vertical-gap" placeholder="First Line">
<input id="fillMeIn4" type="text" required class="form-control vertical-gap" placeholder="Second Line">
<input id="fillMeIn5" type="text" required class="form-control vertical-gap" placeholder="Town/City">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
POST CODE:
<input id="fillMeIn6" type="text" required class="form-control vertical-gap" placeholder="Postcode">
</div>
<div class="col-md-4 vertical-gap">
PHONE No:
<input type="number" class="form-control vertical-gap" placeholder="Tel no">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
EMAIL ADDRESS:
<input id="fillMeIn7" type="email" required class="form-control vertical-gap" placeholder="Email address">
</div>
<div class="col-md-2"></div>
</div>
<div class="row vertical-gap">
<div class="col-md-2"></div>
<div class="col-md-8">
DISCIPLINE:
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Cross Country"> CROSS COUNTRY
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Enduro"> ENDURO
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Downhill"> DOWNHILL
</label>
</div>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-10">
<input id="btnSubmit" type="submit" value="SUBMIT" class="btn btn-success btn-lg">
</div>
<div class="col-md-2"></div>
</div>
</form>
JS:
var formModule = (function () {
var $form = document.getElementById('mbrForm');
var $btn = document.getElementById('btnSubmit');
var $fields = [
document.getElementById('fillMeIn'),
document.getElementById('fillMeIn2'),
document.getElementById('fillMeIn3'),
document.getElementById('fillMeIn4'),
document.getElementById('fillMeIn5'),
document.getElementById('fillMeIn6'),
document.getElementById('fillMeIn7')
];
checkValidation();
$form.addEventListener('change', checkValidation);
$form.addEventListener('keyup', checkValidation);
$fields.forEach(function ($f) {
$f.addEventListener('change', function () {
markInput($f, $f.checkValidity());
});
});
function checkValidation() {
$btn.disabled = !$form.checkValidity();
}
function markInput($field, isValid) {
$field.style.borderColor = isValid ? 'green' : 'red';
}
})();
In this example, the button gets disabled until the form is valid and inputs are validated whenever they are changed.
I added required attribute in HTML inputs so they can be handled by native javascript function checkValidity(). Note that in this case inputs email and number are also correctly checked. You could also use attribute pattern to get a more powerfull validation:
<input type="text" pattern="-?[0-9]*(\.[0-9]+)?">
Hope it helps.
i'm trying to validate my bootstrap form with regex in javascript. I've started the javascript but don't know the right way to continue the validation with my regular expression. I'm trying to validate every input in my form before submitting it.
If anyone could help me with my issue it would be appreciated.
Thank you very much in advance.
In javascript no Jquery please
John Simmons
HTML (This is my html bootstrap form)
<div class="col-md-6">
<div class="well well-sm">
<form class="form-horizontal" id="form" method="post" onsubmit="return validerForm(this)">
<fieldset>
<legend class="text-center header">Contact</legend>
<div class="form-group">
<div class="col-md-10 col-md-offset-1">
<input id="lastName" name="LN" type="text" placeholder="Nom" autofocus class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-md-10 col-md-offset-1">
<input id="firstName" name="FN" type="text" placeholder="Prenom" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-md-10 col-md-offset-1">
<input id="email" name="email" type="text" placeholder="Courriel" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-md-10 col-md-offset-1">
<input id="phone" name="phone" type="text" placeholder="Téléphone" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-md-10 col-md-offset-1">
<textarea class="form-control" id="message" name="Message" placeholder="Entrez votre message. Nous allons vous répondre le plus tôt que possible." rows="7"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
<input class="btn btn-primary btn-lg" type="reset" onclick="clearForm()" value="Clear">
</div>
</div>
</fieldset>
</form>
</div>
</div>
Javascript (this is my javascript with my regexs, I was thinking about doing a function that would verify every value entered with the regex)
var nameregex = /(^[A-Z][a-z]{1,24})+$/;
var emailregex= /^([A-Za-z])([A-Za-z0-9])+\#([a-z0-9\-]{2,})\.([a-z]{2,4})$/;
function validerForm(form) {
window.onload = function(){
document.getElementById('lastName').focus();
}
var valName = Formulaire.name.value;
var valFirst = Formulaire.firstname.value;
var valEmail = Formulaire.email.value;
var nameValide = validationName(valName);
var firstValide = validationFirstName(valFirst);
var emailValide - validationEmail(valEmail);
}
function validationName(valName){
if(nameregex.test(valName) == true){
}else{
}
}
function clearForm() {
document.getElementById("form").reset();
}
You may use string.match()
i.e.: if (valEmail.match(emailregex)) { do stuff!; }