I have first, last name, and email input fields. The requirement from the customer is to have email field required only if either first or last name value exist. If there is no value entered in either of those two fields email should not be required. I have developed this code that works assuming that form is always empty. The problem is the case when user already has data entered in there and user is loading the form. In that case my code is not useful. Here is working example of what I have so far.
$(".check").on("keyup blur", function() {
var fldVal = $(this).val();
if (fldVal) {
$("#email").closest("div").addClass("required");
$("#email").prop("required", true);
} else {
$("#email").closest("div").removeClass("required");
$("#email").prop("required", false);
}
});
.row {padding: 3px;}
.required label:after { content: " *"; color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="text" id="test">
<div class="row">
<label>First Name:</label>
<input type="text" name="first" id="first" class="check">
</div>
<div class="row">
<label>Last Name:</label>
<input type="text" name="last" id="last" class="check">
</div>
<div class="row">
<label>Email:</label>
<input type="email" name="email" id="email">
</div>
<button type="button" name="submit" id="submit">Submit</button>
</form>
I would like for my code to check all the requirements on page load. If possible that should all be done with one function. I can't think of a good way to achieve that. Please let me know if you have any ideas.
Related
The problem
I use a form on a webpage where users fill in all sorts of details. There are 3 fields which generate the input for another field. That field gets generated like this: Firstname + Lastname + Date of birth. However, when a validation error is thrown on the form and the page reloads, the generated input isn't the expected format anymore. Only the Date of birth is then in that input.
It looks like it isn't initializing the Firstname + Lastname field anymore after a validation error is thrown on the page. Any suggestions on how to make it so that the fields gets initialized constantly? Or is there maybe a better way to handle this?
This is the code I use for the generated input
window.onload = function() {
let studentNoField = document.getElementById('input_7_9');
let enteredDetails = {
name: '',
lastname: '',
date: ''
};
/* set value in the third input: Studentnummer */
function generateInput() {
let studentNumber = Object.values(enteredDetails).join('').toLowerCase();
studentNoField.value = studentNumber;
}
/* event listener for first input: Voornaam */
document.getElementById('input_7_1').addEventListener('input', function(event) {
enteredDetails.name = event.target.value.replace(/\s/g, '').slice(0, 8);
generateInput();
});
/* event listener for second input: Achternaam */
document.getElementById('input_7_25').addEventListener('input', function(event) {
enteredDetails.lastname = event.target.value.replace(/\s/g, '').slice(0, 8);
generateInput();
});
/* event listener for second input: Date */
document.getElementById('input_7_3').addEventListener('input', function(event) {
enteredDetails.date = event.target.value.replace(/-/g, '').slice(0, 4);
generateInput();
});
/* Get selected training and format it properly for the PDF */
jQuery('#input_7_23').change(function(e) {
var optionChange = jQuery('#input_7_23 option:selected').text().toUpperCase();
jQuery('#input_7_58').val(optionChange);
});
}
<html>
<body>
<form method="post" enctype="multipart/form-data" id="gform_7" action="/budget/" _lpchecked="1">
<div>
<div id="gform_fields_7">
<div id="field_7_9">
<label for="input_7_9">Studentnummer
<input name="input_9" id="input_7_9" type="text" value="" maxlength="20" aria-required="true" aria-invalid="false">
</div>
</div>
<div id="field_7_1">
<label for="input_7_1">Voornaam</label>
<div><input name="input_1" id="input_7_1" type="text" value="" aria-required="true" aria-invalid="false"> </div>
</div>
<div id="field_7_25">
<label for="input_7_25">Achternaam</label>
<div><input name="input_25" id="input_7_25" type="text" value="" aria-required="true" aria-invalid="false"> </div>
</div>
<div id="field_7_3">
<label for="input_7_3">Geboortedatum</label>
<div>
<input name="input_3" id="input_7_3" type="text" value="" placeholder="dd-mm-yyyy" aria-describedby="input_7_3_date_format" aria-invalid="false" aria-required="true">
<span id="input_7_3_date_format">DD dash MM dash JJJJ</span>
</div>
</div>
</div>
</div>
<div>
<input type="submit" id="gform_submit_button_7" value="Versturen" onclick="if(window["gf_submitting_7"]){return false;} window["gf_submitting_7"]=true; " onkeypress="if( event.keyCode == 13 ){ if(window["gf_submitting_7"]){return false;} window["gf_submitting_7"]=true; jQuery("#gform_7").trigger("submit",[true]); }">
</div>
</form>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Any help or suggestions is appreciated.
There were a few non-existing ids referenced in your code. In the following snippet I have tried to "correct" these errors, but I also went further: I removed all repetitions, thereby following the DRY principle "Don't repeat yourself". The "input"-event listener now works for all elements of the inps array. There is, however one differentiation: the first two elements are limited to 8 characters while the date is limited to 4: .slice(0,i<2?8:4).
const [stNr, ...inps]=[9, 1, 25, 3].map(n=> document.getElementById(`input_7_${n}`));
inps.forEach(inp=>inp.addEventListener("input",()=>
stNr.value=inps.map((el,i)=>
el.value.replace(/[\s-]/g,"").slice(0,i<2?8:4).toLowerCase()
).join(""))
)
<form method="post" enctype="multipart/form-data" id="gform_7" action="/budget/" _lpchecked="1">
<div>
<div id="gform_fields_7">
<div id="field_7_9">
<label for="input_7_9">Studentnummer</label>
<input name="input_9" id="input_7_9" type="text" value="" maxlength="20" aria-required="true" aria-invalid="false">
</div>
</div>
<div id="field_7_1">
<label for="input_7_1">Voornaam</label>
<div><input name="input_1" id="input_7_1" type="text" value="" aria-required="true" aria-invalid="false"> </div>
</div>
<div id="field_7_25">
<label for="input_7_25">Achternaam</label>
<div><input name="input_25" id="input_7_25" type="text" value="" aria-required="true" aria-invalid="false"> </div>
</div>
<div id="field_7_3">
<label for="input_7_3">Geboortedatum</label>
<div>
<input name="input_3" id="input_7_3" type="text" value="" placeholder="dd-mm-yyyy" aria-describedby="input_7_3_date_format" aria-invalid="false" aria-required="true">
<span id="input_7_3_date_format">DD dash MM dash JJJJ</span>
</div>
</div>
</div>
</div>
<div>
<input type="submit" id="gform_submit_button_7" value="Versturen">
</div>
</form>
I removed your jQuery statements at the end of your script, as they referred to non-existent ids. These statements can definitely also be re-written in Vanilla JS, if necessary.
And, as #CherryDT already mentioned: there is no validation code visible here. If it happens on the server then it is the server's responsibility to produce a suitable response that allows the client to render the page with the previously (possibly annotated) content.
I make my JSON script with a form and a button, but when I demo it on someone, they can press the submit button whenever they like. Here is my code:
<form action="action_page.php" method="GET">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"<br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"<br><br>
</form>
All I need now is validation and how to lock or hide the button. I tried using <script> with function and getElementById but I simply do not know how to lock it. Here is the message that will be inputted when it is locked and the form isn't completed:
You have not finished the information input for the survey. Please
input "Your First Name" and "Your Last Name" to enter the survey.
When they finish, I will input a loading icon until fully loaded.
Code Language(s)
I use fiddles to make my code, so I use:
HTML
JSON
Pinch of jQuery (loading icon)
Answer Expectations
In my answers, I need:
Recommended Code Language
Code for note purposes
Crossed out attributes
Attributes before coding explanations
EDIT: I just noticed that I can use the disabled boolean attribute here, so all I need is validation to disable the boolean attribute so they can press the button.
Hello I recommend JavaScript but it is not secure at all. However its the most effective in this case. Here is the code: (Note that i changed the html too)
<form action="action_page.php" method="get" >
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname" onkeyup="inputEntries()"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname" onkeyup="inputEntries()"><br><br>
<button type="submit" name="submit" id="submit_btn" disabled="true">submit</button>
</form>
<script>
var fname_var = document.getElementById("fname");
var lname_var = document.getElementById("lname");
var submit_btn_var = document.getElementById("submit_btn");
function inputEntries(){
if(lname_var.value != "" && fname_var.value != "")
submit_btn_var.disabled = false;
else
submit_btn_var.disabled = true;
}
</script>
What it does is that if both input fields are empty the button is not clickable but if both are it can be clicked. hope it helped!
You can use either pure javascript or jQuery to validate.
In the below code you would see we are first binding a change event to the input field and getting its values. If both values are present, the disabled attribute of the submit button is removed. Else the opposite.
<p id="msg">You have not finished the information input for the survey. Please input "*Your First Name*" and "*Your
Last Name*" to enter the survey.</p>
<form action="action_page.php" method="GET">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"<br><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"<br><br><br>
<button type="submit" id="btn-submit">Submit</button>
</form>
$(document).ready(function(){
('#btn-submit').prop('disabled', true);
$("input[type=text]").change(function(){
if ($('#fname').val() && $('#lname').val()) {
$('#btn-submit').prop('disabled', false);
$('#msg').hide();
} else {
$('#btn-submit').prop('disabled', true);
$('#msg').show();
}
});
});
Stackblitz - https://stackblitz.com/edit/jquery-kgzhuo?file=index.html
I have a some custom validation for a small input form, that checks if a field is required. If it is a required field it alerts the user, if there is no value. At the moment it will validate all inputs other than check boxes.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="ss-item-required">
<label>Question: What is your name?</label>
<input type="text" name="name" id="name"></input>
</div>
<div class="ss-item-required">
<label>Question: What is your email?</label>
<input type="text" name="email" id="email"></input>
</div>
<div class="ss-item-required">
<label>Question: What is your address?</label>
<textarea name="address" rows="8" cols="75" id="address"></textarea>
</div>
<div class="ss-item-required">
<label>Do you agree to out terms?</label>
<input type="checkbox" name="Check_0">
</div>
Submit
</form>
<script>
function formcheck() {
var fields = $(".ss-item-required")
.find("select, textarea, input").serializeArray();
$.each(fields, function(i, field) {
if (!field.value)
alert(field.name + ' is required');
});
console.log(fields);
}
</script>
If anyone can work out how to include validation of check boxes, it would be much appreciated.
Even though some answers already provide a solution, I've decided to give mine, that will validate every required input in your form, regardless of being a checkbox (maintaining your each loop).
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="ss-item-required">
<label>Question: What is your name?</label>
<input type="text" name="name" id="name">
</div>
<div class="ss-item-required">
<label>Question: What is your email?</label>
<input type="text" name="email" id="email">
</div>
<div class="ss-item-required">
<label>Question: What is your address?</label>
<textarea name="address" rows="8" cols="75" id="address"></textarea>
</div>
<div class="ss-item-required">
<label>Do you agree to out terms?</label>
<input type="checkbox" name="Check_0">
</div>
Submit
</form>
<script>
function formcheck() {
var fields = $(".ss-item-required")
$.each(fields, function(i, field) {
field=$(field).find('input, select, textarea')[0]
if (!field.value || (field.type=='checkbox' && !field.checked))
alert(field.name + ' is required');
});
}
</script>
The problems were:
serializeArray() would try to get the value from your checkbox, and because it returned nothing, the checkbox input was never added to fields!
Checkboxes don't have a property value, instead they are checked
There is more than one way to determine this:
Check the length of the JQuery wrapped set that queries for only checked checkboxes and see if it is 1:
if($("input[name='Check_0']:checked").length === 1)
Check the checked property of the DOM element itself (which is what I'm showing below) for false. To extract the DOM element from the JQuery wrapped set, you can pass an index to the wrapped set ([0] in this case), which extracts just that one item as a DOM element and then you can use the standard DOM API.
if(!$("input[type='checkbox']")[0].checked)
NOTE: It's important to understand that all client-side validation can be easily bypassed by anyone who really wants to. As such, you
should always do a second round of validation on the server that will
be receiving the data.
FYI: You have some invalid HTML: There is no closing tag for input elements and for label elements, you must either nest the element that the label is "for" inside of the label or you must add the for attribute to the label and give it a value of the id of the element that the label is "for". I've corrected both of these things below:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="ss-item-required">
<label for="userName">Question: What is your name?</label>
<input type="text" name="userName" id="userName">
</div>
<div class="ss-item-required">
<label for="email">Question: What is your email?</label>
<input type="text" name="email" id="email">
</div>
<div class="ss-item-required">
<label for="address">Question: What is your address?</label>
<textarea name="address" rows="8" cols="75" id="address"></textarea>
</div>
<div class="ss-item-required">
<label for="Check_0">Do you agree to out terms?
<input type="checkbox" name="Check_0">
</label>
</div>
Submit
</form>
<script>
function formcheck() {
var fields = $(".ss-item-required")
.find("select, textarea, input").serializeArray();
$.each(fields, function(i, field) {
if (!field.value){
alert(field.name + ' is required');
}
});
// Check to see if the input is a checkbox and if it's checked
if(!$("input[type='checkbox']")[0].checked){
alert("You must agree to the terms to continue.");
}
}
</script>
Personally (and I'm far from alone on this), the use of JQuery is way overused in today's world. When it came out, the standard DOM API wasn't as mature as it is now and JQuery made DOM element selection and manipulation very simple. Back then, JQuery was a Godsend.
Today, the DOM API has matured and much of what we use to rely on JQuery to make easy, can be done just as easily without JQuery. This means you don't have to reference the JQuery library at all (faster page loading) and you're code follows standards.
If you're interested, here's your code without JQuery:
<form>
<div class="ss-item-required">
<label for="userName">Question: What is your name?</label>
<input type="text" name="name" id="userName">
</div>
<div class="ss-item-required">
<label for="email">Question: What is your email?</label>
<input type="text" name="email" id="email">
</div>
<div class="ss-item-required">
<label for="address">Question: What is your address?</label>
<textarea name="address" rows="8" cols="75" id="address"></textarea>
</div>
<div class="ss-item-required">
<label for="Check_0">Do you agree to out terms?
<input type="checkbox" name="Check_0">
</label>
</div>
Submit
</form>
<script>
function formcheck() {
// Get all the required elements into an Array
var fields = [].slice.call(document.querySelectorAll(".ss-item-required > *"));
// Loop over the array:
fields.forEach(function(field) {
// Check for text boxes or textareas that have no value
if ((field.type === "text" || field.nodeName.toLowerCase() === "textarea")
&& !field.value){
alert(field.name + ' is required');
// Then check for checkboxes that aren't checked
} else if(field.type === "checkbox" && !field.checked){
alert("You must agree to the terms to continue.");
}
});
}
</script>
I have a form to submit several fields. Two of them are for changing a password.
These password fields aren't required to be filled out before submitting. However, if one of them isn't blank I add the required attribute to both fields when it's changed through jQuery. I remove the attributes when I empty one and the other is already empty too.
The thing it seems to work the most of the times with an exception:
I fill out password
password2 is blank
I submit the form
In this case the validation for password2 shows up, but if I want to remove everything and submit, I can't:
I remove password
I submit the form again
The validation for password2 shows up again. Even if the 'required' attributed is removed in the HTML source
This is the HTML code:
<form id="edicionPerfilForm" action="actor/edit.do" method="post">
<div class="row">
<div class="form-group col-md-4">
<div>
<label for="password">Password</label>
<input id="password" name="password" class="form-control" type="password" value="" oninvalid="this.setCustomValidity('Fill out this field')" oninput="this.setCustomValidity('')">
<br>
</div>
</div>
<div class="form-group col-md-4">
<div>
<label for="password2">Repeat password</label>
<input id="password2" name="password2" class="form-control" type="password" value="" oninvalid="this.setCustomValidity('Fill out this field')" oninput="this.setCustomValidity('')">
</div>
</div>
</div>
<button name="save" type="submit" class="btn btn-dark">Send</button>
</form>
And the jQuery code:
$('#password').change(function() {
if($(this).val() != ''){
$(this).attr('required', true);
$( '#password2' ).attr('required', true);
}else{
if($('#password2').val() == ''){
$(this).removeAttr('required');
$( '#password2' ).removeAttr('required');
}
}
});
$('#password2').change(function() {
if($(this).val() != ''){
$(this).attr('required', true);
$('#password').attr('required', true);
}else{
if($('#password').val() == ''){
$(this).removeAttr('required');
$('#password').removeAttr('required');
}
}
});
And it's an example in JSFiddle:
https://jsfiddle.net/jke3pgh0/
I will suggest you a different approach here...
First, you only need one handler for this, since the logic is the same for both inputs. You can use more than one selector... Ex: $('#password, #password2'). But I would use a class instead... Like $(".password"). It's up to you.
Second, I said the «logic is the same»... That is:
If one of the two inputs is not empty, both are required.
So having the same change event handler on both inputs mean you don't really know which one triggered the event. So I suggest to use an .each() loop here (to make sure you check all values)... and a boolean "flag" (true/false).
After that loop, use that "flag" to set the required attribute.
I used a CSS rule to make the result obvious in the snippet below.
$('#password, #password2').change(function(){
// Look up for the password inputs in that "row".
var pass_inputs = $(this).closest(".row").find("[type='password']");
// Flag to determine if at least one is not empty.
var not_empty = false;
// Loop throug the password inputs and change the flag.
pass_inputs.each(function(){
if($(this).val() != ''){
not_empty = true
}
});
// Use the flag as the boolean argument for the required attribute.
pass_inputs.attr('required', not_empty);
});
[required]{
border: 3px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="edicionPerfilForm" action="actor/edit.do" method="post">
<div class="row">
<div class="form-group col-md-4">
<div>
<label for="password">Password</label>
<input id="password" name="password" class="form-control" type="password" value="" oninvalid="this.setCustomValidity('Fill out this field')" oninput="this.setCustomValidity('')">
<br>
</div>
</div>
<div class="form-group col-md-4">
<div>
<label for="password2">Repeat password</label>
<input id="password2" name="password2" class="form-control" type="password" value="" oninvalid="this.setCustomValidity('Fill out this field')" oninput="this.setCustomValidity('')">
</div>
</div>
</div>
<button name="save" type="submit" class="btn btn-dark">Send</button>
</form>
Here, In my code First name and Last name fields placed side by side how to write a validation for that 2 fields i tried but am not getting correct.I attached image and my code below
jQuery code:
jQuery(function(){
jQuery("#fName").validate({
expression: "if (VAL.match(/^[a-zA-Z]{2,30}$/)) return true; else return false;",
message: "Please enter the First Name Last Name"
});
});
signup.html
<div class="form-fullname">
<input class ="first-name"type="text" id="fName" name="firstname" placeholder="First name" required="">
<input class="last-name" type="text" id="lName" name="lastname" placeholder="Last name" required="">
</div>
The full page is an error image.
Error:
in this signup form when am entered numbers in first name it should show error message at below, but it is showing beside first name as shown in picture. So can you tell me how can i get error message in below.
Try to add the regex on input tag Instead:
<form action="register_page">
<div class="form-fullname">
<input class ="first-name" type="text" id="fName" name="firstname" placeholder="First name" pattern="^\w{2,30}$" required>
<input class="last-name" type="text" id="lName" name="lastname" placeholder="Last name" pattern="^\w{2,30}$" required>
</div>
<input type="submit" value="Register">
</form>
Note that you can use \w on regex instead of [a-zA-Z]. This way you don't need jquery validation in this case.
You can use test function on the regular expression in JavaScript to know whether the input is in valid format.
Use css function to display or hide the error messages.
If you want to show error for first name field when last name field is focused you can write an on focus event in jQuery.
$(document).ready(function () {
var NAME_REGEX = /^[a-zA-Z]{2,30}$/;
$('#signupBtn').click(signupBtnClick);
$('input[name="lastname"]').focus(lastNameOnFocus);
function signupBtnClick() {
validateFirstName();
validateLastName();
}
function lastNameOnFocus() {
validateFirstName();
}
function validateFirstName() {
var firstName = $('input[name="firstname"]').val();
if(NAME_REGEX.test(firstName)) {
$('#firstnameerror').css('display', 'none');
} else {
$('#firstnameerror').css('display', 'block');
}
}
function validateLastName () {
var lastName = $('input[name="lastname"]').val();
if(NAME_REGEX.test(lastName)) {
$('#lastnameerror').css('display', 'none');
} else {
$('#lastnameerror').css('display', 'block');
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div>
<h3>Sign Up</h3>
</div>
<div>
<input type="text" name="firstname" placeholder="First Name">
<span id="firstnameerror" style="color: red; display: none;">First Name is required</span>
</div>
<div style="margin-top: 1%;">
<input type="text" name="lastname" placeholder="Last Name">
<span id="lastnameerror" style="color: red; display: none;">Last Name is required</span>
</div>
<div style="margin-top: 2%;">
<button type="button" id="signupBtn">Submit</button>
</div>