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();
});
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 have a textbox called 'Label' and another select box called 'Validation'. When I click on the add button, the value of the textbox 'Label' appends to the form on left with a newly created textbox like this.
Now what I am trying to do is, I'm trying to add validation to the dynamically created textbox from the list of validation options available in the select box in the form on right(alphabets or numbers).
ie, when I type 'New Age' and select 'Numeric' as validation, the 'New Age:' text box created on the left form should only submit if it input is a number. Otherwise display error.
Thanks in advance.
<!DOCTYPE html>
<html>
<head>
<!--<link rel="stylesheet" href="styless.css">-->
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script>
var Errors = [];
</script>
<script src="newfunc.js"></script>
<script>
$(document).ready(function () {
$("#name").on("input", function () {
nameCheck();
});
$("#age").on("input", function () {
ageCheck();
});
$("#gender").on("input", function () {
genderCheck();
});
$("#vehicle").on("input ", function () {
vehicleCheck();
});
$("#cars").on("input", function () {
carsCheck();
});
var x = 1;
function appendRow() {
var d = document.getElementById('divis');
d.innerHTML += "<input type='text' id='tst" + x++ + "'><br >";
}
$("form[name='form1']").on("submit", function (event) {
if (!nameCheck()) {
Errors.push("Please enter a valid name");
event.preventDefault();
}
if (!ageCheck()) {
Errors.push("Please enter a valid age");
event.preventDefault();
}
if (!genderCheck()) {
Errors.push("Please select gender");
event.preventDefault();
}
if (!carsCheck()) {
Errors.push("Please select a valid make");
event.preventDefault();
console.log(Errors);
}
if (!vehicleCheck()) {
Errors.push("Please check a mode");
event.preventDefault();
} else {
$(this).trigger("submit");
}
});
$("form[name='form2']").on("submit", function (event) {
var lab = $("#label").val();
$('#divis').append(lab);
appendRow();
$('#ol_div').append($('#todd'));
// $('#dono').remove();
event.preventDefault();
});
});
</script>
<style>
.error p {
display: inline-block;
color: red;
}
form p {
display: none;
}
.inlineinput div {
display: inline;
}
.one {
display: inline;
}
.two {
display: inline;
}
</style>
</head>
<body>
<div class="main" style="width:100%;">
<div id="old_div" style="float:left; width:50%;">
<form name="form1" action="fun.php" method="post" onsubmit="validateAllInputBoxes(event);">
<div class="name">
<label>Name : </label>
<input id='name' name='dedede' type='text'><br>
<p id="p1"></p>
</div>
<br>
<div class="age">
<label>Age : </label>
<input id='age' name='subject' type='text'><br>
<p id="p2"></p>
</div>
<br>
<div class="gender">
<label>Gender : </label>
<input id='gender' type='radio' name='sel' value='male'>Male
<input id='gender' type='radio' name='sel' value='female'>Female<br>
<p id="p3"></p>
</div>
<br>
<div class="vehicle">
<label>Vehicle : </label>
<input type="checkbox" id="vehicle" name='vehicle' value="Car">Car
<input type="checkbox" id="vehicle" name='vehicle' value="Bike">Bike
<input type="checkbox" id="vehicle" name='vehicle' value="Other">Other<br>
<p id="p4"></p>
</div>
<br>
<div class="cars">
<label>Car Make:</label>
<select name="cars" id="cars" ">
<option value="-1" selected disabled="disabled">Choose an option</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
<br>
<p id="p5"></p>
</div>
<br>
<div id="ol_div">
</div>
<div>
<button id="submit" class="sendButton">Submit</button>
</div>
</form>
<br/>
</div>
<div style="float:right; width:50%; ">
<div id="new_div">
<form name="form2" method="post">
<span class="inlineinput">
<div class="name">
<label>Label : </label>
<input id='label' name='dedede' type='text'>
</div>
</span>
<span class="inlineinput">
<div class="name">
<label>Validation:</label>
<select name="vali" id="vali" ">
<option value="-1" selected disabled="disabled">Choose an option</option>
<option value="1">Numerics</option>
</select>
</div>
</span>
<span class="inlineinput">
<div>
<button id="dono" class="newButton">Add</button>
</div>
</span>
<br>
<br>
<div id="todd">
<div class="one" id="labe"></div>
<div class="two" id="divis"></div>
<br><br>
</div>
<br>
</form>
</div>
</div>
</body>
</html>
newfunc.js
function nameCheck() {
var name = $('#name').val();
var name_regex = /^[A-z]+$/;
if (!name_regex.test(name)) {
$('#p1').text("* Please enter a valid name *");
$("#name").parents(".name").addClass("error");
return false;
} else {
$("#name").parents(".name").removeClass("error");
return true;
}
}
function ageCheck() {
var age = $('#age').val();
var age_regex = /^[0-9]+$/;
if (!age_regex.test(age)) {
//Errors.push("Please enter a valid age");
$('#p2').text("* Please enter a valid age *");
$("#age").parents(".age").addClass("error");
return false;
} else {
$("#age").parents(".age").removeClass("error");
return true;
}
}
function labelCheck() {
var label = $('#label');
if (label.val().length > 0) {
//Errors.push("Please enter a valid age");
$('#p2').text("* Please enter a valid label *");
$("#label").parents(".label").addClass("error");
return false;
} else {
$("#label").parents(".label").removeClass("error");
return true;
}
}
function genderCheck() {
var gender = $('#gender').val();
if ($('input[type=radio]:checked').length <= 0) {
//Errors.push("Please select Gender");
$('#p3').text("* Please select the Gender *");
$("#gender").parents(".gender").addClass("error");
return false;
} else {
$("#gender").parents(".gender").removeClass("error");
return true;
}
}
function vehicleCheck() {
var vehicle = $('#vehicle').val();
if ($('input[id=vehicle]:checked').length == 0)
{
//Errors.push("Please select a vehicle");
$('#p4').text("* Please select a vehicle *");
$("#vehicle").parents(".vehicle").addClass("error");
return false;
} else {
$("#vehicle").parents(".vehicle").removeClass("error");
return true;
}
}
function carsCheck() {
var cars = $('#cars').val();
if (document.form1.cars.value == "-1")
{
//Errors.push("Please select one car make");
$('#p5').text("* Please select one car make *");
$("#cars").parents(".cars").addClass("error");
return false;
} else {
$("#cars").parents(".cars").removeClass("error");
return true;
}
}
(function ($) {
$.fn.selected = function (fn) {
return this.each(function () {
$(this).focus(function () {
this.dataChanged = false;
}).change(function () {
this.dataChanged = true;
fn(this);
}).blur(function (e) {
if (!this.dataChanged) {
fn(this);
}
});
});
};
})(jQuery);
In your case, I would probably add an array called validations and push a new validation function on it every time you add a new text box. On submit, I'd check each function in the validations array and output possible errors. If there was no error, submit, otherwise show the errors.
You could create a function that returns a validation function. For example:
function createNumericValidationForField($yourNewElement) {
return function () {
// your logic here, for example:
try {
return { result: parseInt($yourNewElement.value()) };
} catch (err) {
return { error: err };
}
};
}
Then you can go through the validations array, call each of these functions and check if there is a result or error inside the returned objects.
Well, you can do this in multiple ways.
1. Write a validation for every input field you want to implement
The most efficient way for this would be to write checks with RegEx like this:
Numbers
const numbers = new RegExp(/^[0-9]+$/);
numbers.test(yourString)
Characters
const characters = new RegExp(/^[a-zA-Z]*$/);
characters.test(yourString);
The test() function returns either true or false when checking your variable against the specified RegExp.
You can do this on every onChange() event the input calls to have a nice and fast response for the user, or you can use it right before submitting the form.
You can add this to the onChange() event while constructing your input field, like this:
var newObject = document.createElement('input');
newObject.onchange = numberValidation();
2. Change the input type when you construct it
As you are dynamically create your label and input fields you can easily change that inputs type:
var newObject = document.createElement('input');
newObject.type = 'password'; // can be password, number, tel, etc.
These input types prevent typing wrong values.
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;
}
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>
I am using javascript validations for required field. Here is my html
<form class="uk-form-stacked" name="myForm" action="<?php echo base_url(); ?>admin/pages/create_service" id="wizard_advanced_form" method="post" enctype="multipart/form-data" onsubmit="return myFunction(this)" novalidate>
<div data-uk-grid-margin="" class="uk-grid">
<div class="uk-width-medium-1-2">
<label for="service_title">Service Title<span class="req">*</span></label>
<input type="text" name="service_title" id="validd" class="md-input" />
<p id="demo"></p>
</div>
</div>
<div class="uk-grid">
<button type="submit" class="md-btn md-btn-primary md-btn-wave-light waves-effect waves-button waves-light" >Submit</button>
</div>
</form>
my javascript is
<script>
function myFunction(form) {
var x, text;
x = document.getElementById("validd").value;
if (x == null || x == "") {
text = "Input not valid";
}
document.getElementById("demo").innerHTML = text;
return false;
}
</script>
Now when my input field is empty and i submit form it shows me input not valid that is fine. but even when i fill some textin input then it shows me undefined in place of input not valid instead of submitting form.
please help..
You forgot to add an else where it would return true if the condition is not satisfied.
<script>
function myFunction(form) {
var x, text;
x = document.getElementById("validd").value;
if (x == null || x == "") {
text = "Input not valid";
document.getElementById("demo").innerHTML = text;
return false;
}
else{
return true;
}
}
</script>
You can use instead:
<html>
<head>
<script>
function valid()
{
var x;
x=document.getElementById(validd).value;
if(x==null || x=="")
{
alert("Please input service title");
document.getElementById(validd).focus();
return false;
}
}
</script>
</head>
<body>
<form name="myForm" onsubmit="return valid()">
<input type="text" name="service_title" id="validd"/>
<button type="submit">Submit</button>
</form>
</body>
</html>`