I have a form with 3 text inputs with function to validate them on submit like this:
<form action="" method="post" onSubmit="return checkForm(this.form)">
and checkForm():
var pattern_name = /^([a-zA-Z\u00C0-\u00FF]+[ '-]?[a-zA-Z\u00C0-\u00FF]+){1,30}$/;
var pattern_email = /^[_a-z0-9-]+(.[_a-z0-9-]+)*#[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4})$/;
function checkForm(){
$("form.formul :input[type=text]").each(function(){
var input = $(this);
var value = input.val();
if (value=="") {
console.log("l'input est vide");
return false;
}
else{
console.log(value);
return false;
}
});
}
.info-user{
display: flex;
flex-direction: column;
}
.info-user input{
width: 50%;
height: 30px;
margin: 10px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" onSubmit="return checkForm(this.form)">
<div class="civilite">
<input type="radio" name="civ" value="Mme." id="mme" class="inline-radio"/>
<label for="mme" class="civ-radio">Mme</label>
<input type="radio" name="civ" value="Mlle." id="mlle" class="inline-radio"/>
<label for="mlle" class="civ-radio">Mlle</label>
<input type="radio" name="civ" value="M." id="m" class="inline-radio"/>
<label for="m" class="civ-radio">M</label>
</div>
<div class="info-user">
<input type="text" name="prenom" placeholder="Prénom"/>
<input type="text" name="nom" placeholder="Nom"/>
<input type="text" name="email" placeholder="E-mail"/>
<input type="image" name="image" value="submit" id="cta" />
</div>
</form>
but when validating the form on submit, the console say: "l'input est vide" and reload the form...
I want to stop the validation until the form is valid
If I need to send the false statement to the function checkForm, I must transmit the false statement through the .each function?
like this?
function checkForm(e){
if(e == false){
return false;
}
$("form.formul :input[type=text]").each(function(){
var input = $(this);
var value = input.val();
if (value=="") {
console.log("l'input est vide");
checkForm(false);
}
else{
console.log(value);
}
});
}
it's not a little weird?
you should return the result of validation in checkForm.
try this:
function checkForm(){
var isValid = true;
$("form.formul :input[type=text]").each(function(){
var input = $(this);
var value = input.val();
if (value=="") {
// input is required!
console.log("l'input est vide");
isValid = false;
}
else{
console.log(value);
return false;
}
});
return isValid;
}
Related
I am trying to validate the text input in my html. I only want alphabets and spaces. In the beginning, the validation worked but now it is not and I cannot seem to find the problem. It still submits the form with the invalid field. Please see the code below
index.html
<div class="full-form">
<form class=form-info action="cv.html" onsubmit="return handlesubmit()" >
<div class="f-header">
SIGN UP
</div>
<div class="bdetails">
<label for="fname">First Name</label><br>
<input type="text" name="fname" id="f_name" placeholder="First Name" onfocus="checkFName()" onblur="BlurFName()" required><br>
<p class="error_message" id="First_em">Name must contain only alphabets(A-Z)</p>
</div>
<script type="text/javascript" src="test.js"></script>
</form>
test.js
function checkData(){
if(BlurFName()){
}
return false;
}
function handlesubmit(){
checkData();
passvalue();
}
/*
Function to check if the name inputted is valid when the input is focused
*/
function checkFName(){
let name_len=/^[A-Za-z]+$/;
let fname= document.getElementById("f_name");
if(!fname.value.match(name_len)){
document.getElementById("First_em").style.display = "inline";
return true;
}
};
/*
Function to check if the name inputted is valid when the input is blurred
*/
function BlurFName(){
let name_len=/^[A-Za-z]+$/;
let fname= document.getElementById("f_name");
if(fname.value.match(name_len)){
document.getElementById("First_em").style.display = "none";
return false;
}
};
With function handlesubmit you need to return false or true.
I suggest use
e.preventDefault();
to easier handle Form submiting
You are not returning anything from your validation method. You need to do something like this:
function validateName () {
const inp = document.getElementById("fname");
const isValid = inp.value.trim().length > 0;
inp.classList.toggle('error', !isValid);
return isValid;
}
function validateGuess () {
const inp = document.getElementById("guess");
const isValid = +inp.value.trim() > 10;
inp.classList.toggle('error', !isValid);
return isValid;
}
function validate () {
const isNameValid = validateName();
const isGuessValid = validateGuess();
return isNameValid && isGuessValid;
}
.error { border-color: red; }
<form onsubmit="return validate()">
<label for="fname">name</label> <input type="text" name="fname" id="fname" /><br/>
<label for="guess">guess</label> <input type="number" name="guess" id="guess" />
<button>Submit</button>
</form>
I am trying to validate a form using javascript but I can change border color when the if statement looking at the password(login_pass) is not included in the script but when added nothing works. I referred to the bootstrap form validation as well but could not understand why nothing works when I add the second if statement with login_pass.
Here is the form html:
<form id="needs-validation" name="account" action="" method="POST" novalidate>
<div class="form-group" style="margin: auto;">
<label for="user">User Name</label>
<input id="login_uname" type="text" class="form-control" placeholder="User Name" value="" name="user" required>
</div>
<div class="form-group" style="margin: auto;">
<label for="pwd">Password</label>
<input id="login_password" type="password" class="form-control" placeholder="Password" value="" name="pwd" required>
</div>
<button id="login_submit" style="margin-right: 10%; float: right;" type="submit" class="btn btn-default">Log In</button>
</form>
Here is my javascript:
var form = document.getElementById('needs-validation');
var login_user = document.getElementById('login_uname');
var login_pass = document.getElementById('login_pass');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
if(login_user.value === "") {
login_user.style.borderColor = 'red';
} else {
login_user.style.borderColor = 'green';
}
if(login_pass.value === "") {
login_pass.style.borderColor = 'red';
} else {
login_pass.style.borderColor = 'green';
}
event.preventDefault();
event.stopPropagation();
} else {
form.classList.add('was-validated');
}
}, false);
Besides the typo in the id of password field you could use ValidityState in your syntax like in the example below. It would be better for handling input errors e.g. a pattern mismatch error.
var form = document.getElementById('needs-validation');
var login_user = document.getElementById('login_uname');
var login_pass = document.getElementById('login_password');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
if (login_user.validity.valueMissing) {
login_user.style.borderColor = 'red';
} else {
login_user.style.borderColor = 'green';
}
if(login_pass.validity.valueMissing) {
login_pass.style.borderColor = 'red';
} else {
login_pass.style.borderColor = 'green';
}
event.preventDefault();
event.stopPropagation();
} else {
form.classList.add('was-validated');
}
}, false);
Change
var login_pass = document.getElementById('login_pass');
to
var login_pass = document.getElementById('login_password');
html
<form action="" id="formsave">
<div class="row">
<input type="text" id="test1"name="test1">
<input type="text" id="test2"name="test2">
</div>
</form>
I have two input fields, If test1 have a value it required test2 if not it would not required. It means if test1 is have a value, you cannot save the form without test2 value. if test1 is null test2 is not required.
Try this
<html>
<head>
<script>
function check() {
var test1 = document.getElementById("test1").value
var test2 = document.getElementById("test2").value
if ((!!test1 && !!test2) || !test1) {
return true
} else {
document.getElementById("errmsg").innerHTML = "test2 required"
return false
}
}
</script>
</head>
<body>
<form onsubmit="return check()">
<input type="text" id="test1">
<input type="text" id="test2">
<input type="submit">
<div id="errmsg"></div>
</form>
</body>
</html>
Check the value of test1 when the form is saved.
$("#save").on('click', function() {
if($("#test1").val()) {
alert("please enter all data");
} else {
$("#formsave").submit();
}
});
Something like that
var form = document.getElementById('formsave'),
check = function() {
var input1 = document.getElementById('test1'),
input2 = document.getElementById('test2');
if (input1.value !== '' && input2.value === '') {
return false;
} else return true;
};
form.addEventListener('submit', function(e) {
if (check()) {
// do stuff here
} else e.preventDefault();
});
I have a list of form input elements on which I want to run a loop. From the result, I need to run a few conditional statements so that I can validate them using their name attributes. I've used jQuery for that and used .each method for looping through them. Thus I can add/remove class name to invalid input elements.
It's little difficult to describe in words. But the code block bellow will make sense:
JSFiddle
function formValid() {
var valid = true;
$('form input').each(function() {
if ($(this).val() == '') {
valid = false;
$(this).addClass('red-border');
} else if (true /* if "tel" is not a number */ ) { // <- here I want to validate using input name attribute
valid = false;
$(this).addClass('red-border');
} else {
$(this).removeClass('red-border');
}
});
return valid;
}
$('form').on('submit', function(event) {
event.preventDefault();
if (formValid()) {
alert('Yay!');
}
});
.red-border {
border-color: red !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#">
<p>
<input type="text" name="name">
</p>
<p>
<input type="text" name="tel">
</p>
<p>
<input type="text" name="email">
</p>
<p>
<button type="submit">Submit</button>
</p>
</form>
Check out the fiddle
https://jsfiddle.net/t9ayvken/
CSS:
.red-border {
border-color: red;
}
HTML:
<form action="#">
<p>
<input class="must-validate" type="text" name="name">
</p>
<p>
<input class="must-validate" type="text" name="tel">
</p>
<p>
<input class="must-validate" type="text" name="email">
</p>
<p>
<button type="submit">Submit</button>
</p>
</form>
JQuery:
/*validation functions for each input type*/
function validateName(event){
var $this = $(this);
/* validation is done here */
if(false){
$this.removeClass('red-border');
}
else {
/* not valid*/
$this.addClass('red-border');
}
}
function validateTel(event){
}
function validateEmail(event){
}
/*add validation event handlers*/
$(document).on('validate','[name="name"]',validateName);
$(document).on('validate','[name="tel"]',validateTel);
$(document).on('validate','[name="email"]',validateEmail);
function formValid() {
var valid = true;
/*Trigger validation events for all required inputs*/
$('input.must-validate').trigger('validate');
/* After validation is complete check to see if any are invalid */
if( $('input.must-validate.red-border').length ){
alert('the form is invalid');
valid = false;
}
return false;
//return valid;
}
$('form').on('submit', function(event) {
event.preventDefault();
if ( formValid() ) {
alert('Yay!');
}
});
I suggest returning a list of errors instead of a boolean flag.
function formValid() {
var errorMsgs = [];
$('form input').each(function() {
var msg = [],
val = $(this).val();
// Check blanks
if (val == '')
msg.push( `${$(this).attr('name')} is blank`);
// Check numbers
if ($(this).attr('name') === 'tel' && isNaN(val))
msg.push( `${$(this).attr('name')} is not a number`);
// Handle results
if (msg.length > 0){
errorMsgs.push(...msg);
$(this).addClass('red-border');
} else {
$(this).removeClass('red-border');
}
});
return errorMsgs;
}
$('button').on('click', function(event) {
var errors = formValid();
if (errors.length === 0) {
alert('Yay!');
} else {
alert(errors.join('\r'));
}
});
.red-border {
border-color: red !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#">
<p>
<input type="text" name="name">
</p>
<p>
<input type="text" name="tel">
</p>
<p>
<input type="text" name="email">
</p>
<p>
<button type="submit">Submit</button>
</p>
</form>
How to get an Alert on Submit when I left a TextBox empty And It Should Turn To the Next page on submit.
Must Reply,
Thank You.
You can try this :
HTML :
<form action="" method="POST" id="myForm">
<input id="myInput" type="text" />
<input type="submit" />
</form>
(Replace the action attribute by the url of your destination page, the one you call the "next page").
JS (without jQuery):
var myForm = document.querySelector('#myForm');
var myInput = document.querySelector('#myInput');
myForm.addEventListener('submit', function(pEvent) {
if(myInput.value === '') {
pEvent.preventDefault(); //Prevents the form to be sent
alert('Ho! Stop!');
//Do whatever you want
}
});
JS (with jQuery) :
var myForm = $('#myForm');
var myInput = $('#myInput');
myForm.on('submit', function(pEvent) {
if(myInput.val() === '') {
pEvent.preventDefault(); //Prevents the form to be sent
alert('Ho! Stop!');
}
});
Demo : http://jsfiddle.net/af9qvkmp/9/
Here is the demo, based on jQuery!
HTML
<form action="" method="POST" id="form">
<input id="input1" type="text" />
<input id="input2" type="text" />
<input id="input3" type="text" />
<input id="input4" type="text" />
<input id="input5" type="text" />
<input type="submit" />
</form>
JS
$(function() {
$('#form').on('submit', function(event) {
var isError = false;
$(this).find('input[type="text"]').each(function() {
if($(this).val() == '') {
console.log($(this));
isError = true;
return false;
}
});
if(isError) {
event.preventDefault();
alert("Got Error");
} else {
// Submit the form
}
});
});
In form tag write
<form action="" method="post" enctype="multipart/form-data" onsubmit="return checkform(this);">
This is your input field
<input type="text" name="reviewValue" value="" id='starRate2' required>
Javascript Code:
<script language="JavaScript" type="text/javascript">
function checkform ( form ){
if (form.reviewValue.value == "") {
alert( "Please choice your Rating." );
form.reviewValue.focus();
return false ;
}
return true ;
}
</script>