Focus on first invalid text field after form validation - javascript

I have a pretty standard HTML form in which I collect user input. I have a submit button that will run a JavaScript function (onClick) that in turn validate the data entered by the users.
The function looks like this:
function validateForm()
{
var isValid = true;
var txtFirstname = document.getElementById("firstName").value;
var txtLastname = document.getElementById("lastName").value;
(etc...)
/*Validate First Name*/
if(txtFirstname.length <= 0){
document.getElementById("lblFirstName").innerHTML=" *";
isValid = false;
}
else{
document.getElementById("lblFirstName").innerHTML="";
document.getElementById("firstName").value = txtFirstname;
}
/*Validate last Name*/
if(txtLastname.length <= 0){
document.getElementById("lblLastName").innerHTML=" *";
isValid = false;
}
else{
document.getElementById("lblLastName").innerHTML="";
document.getElementById("lastName").value = txtLastname;
}
(etc...)
if(isValid){
document.formX.submit();
}
else{
return false
}
}
My question is: how can I set the focus on the first "invalid" textbox after the function has validated the form?
Thanks,
Eric

i search 4 it & find a better popular solution :
`$("#"+document.querySelectorAll(":invalid")[1].id).focus();`
it's work for me. note that index of first invalid input in Firefox is 1 not 0. because of in FF the form is invalid and count, when an invalid input exist.

It would be cleaner if you functionally decomposed your validation. Then you could have a variable called "firstInvalidField" which is initially set to null. Upon invalidation of a field, check to see if firstInvalidField is null, if it is, set it to the textBox in question. If it is not null, skip over the code.
After the validation is complete, if the firstInvalidField variable is not null, call .focus() on it.

Related

Two text fields, only one required to be filled (either)

So I have two fields in my webpage, one for telephone number and the other for email address, I need to make either one of them required to be filled by using JavaScript NOT jQuery. Most of the answers I found here are for jQuery, any solutions with JavaScript would be much appreciated. Thanks!
function User_one(){
var phone = document.getElementById('PhoneText2').value;
var mail = document.getElementById('EmailText1').value;
if (phone && mail == ""){
alert("An error occurred.");
}else{
return false;
}
}
Update with actual code
Here's how I'd do it
(function () {
document.getElementById('myForm').addEventListener('submit', function(event){
// Get the length of the values of each input
var phone = document.getElementById('PhoneText2').value.length,
email = document.getElementById('EmailText1').value.length;
// If both fields are empty stop the form from submitting
if( phone === 0 && email === 0 ) {
event.preventDefault();
}
}, false);
})();
Since you haven't supplied any code for us to work with, I'll answer in pseudo-code:
On form submission {
If (both telephone and email is empty) {
throw validation error
}
otherwise {
submit the form
}
}
If you show me your code I'll show you mine :-)

Need to validate with range and by pass validation function with session value if user want to enter value beyond range

I have multiple input type text on jsp form for each the range is defined to the next input type textbox i want to validate with the defined range and if the value beyond the range validation function ask for pop confirmation if user enter userid in text that compare with session value ie 'user' then the validation function allow user to submit form with return true and not ask again for that filed validate .how can i achieve this using javascript function.any other way that can i achieve same using javascript .Request you to Suggest Option with example code.
JavaScript code:-
if(document.getElementById('pH'+formid).value !=0)
{
var user;
var value=document.getElementById('pH'+formid).value;
var maxmin=document.getElementById('pHspecf'+formid).value.split('-');
var max=maxmin[0];
var min=maxmin[1];
if(value<min||value>mix)
{
alert("max-"+max+" min-"+min+" value of parameter-"+value);
var c=confirm("Entered Value Beyond the Specification Range.\n DO you Still Want To continue Press Yes..!");
if (c==true)
{
var person=prompt("Please enter your Username","Your User name");
if (person!=null)
{user=person;
alert("Hello "+person+" Your Request Is Accepted..!");
}else{
document.getElementById('pH'+formid).style.backgroundColor = "lightblue";
document.getElementById('pH'+formid).focus();
return false;
}
}
else
{
document.getElementById('pH'+formid).focus();
return false;
}
}
}

JS->Form validation on inputs. Using for loop to get all the inputs index

I have a form with 4 inputs and I want to show an alert on submit. What I have done is that I have already created the warnings that goes under every input with display:none; in CSS.
After this I have created a for loop in JS to get the index of every input and apply my if statement of showing the the alert if === null || === ""
using a variable to make the querySelector("THE CLASS").style.display="block";
Also on my form I have this line
<form method="post" class="q-form" name="form" onsubmit="return validate()">
My problem is when I submit my form the only alert that is shown is the one under the Username and after it appears it also disappears because I think that the for loop goes to the next input.
Let me know if there is something more to clarify.
Here you have all the code: https://jsbin.com/kazopahuga/1/edit?html,js,output
If you want to see the alert showing press Run with JS
Thank You!
I suggest a few modifications to your validare() function:
Add a flag indicating whether the whole form is valid, assume it's true until you find an input that is invalid. Return the value of this flag.
var isValid = true;
Capture your validation messages too so you can access them by index like your inputs:
messages = document.getElementsByClassName(' alert alert-danger custom');
When you find an invalid input, display the associated message and update the valid flag to false.
if (currentInputValue == null || currentInputValue === "") {
messages[index].style.display = "block";
isValid = false;
}
Here is the updated function:
function validare() {
var inputs, messages, index;
var isValid = true;
inputs = document.getElementsByTagName('input');
messages = document.getElementsByClassName(' alert alert-danger custom');
for (index = 0; index < inputs.length; ++index) {
var currentInputValue = inputs[index].value;
if (currentInputValue == null || currentInputValue === "") {
messages[index].style.display = "block";
isValid = false;
}
}
return isValid;
}
Updated jsbin here
Here is an updated solution: jsbin
You used querySelector which return only the first element it finds with the same class, you should have used querySelectorAll which return all the selectors.

Is there a way to reverse the suspension of form-submission or will it be better not to have it done in the first place?

I am trying to make a simple web application. In my login page I have a form with a text field, a password and a submit button. Form submission is prevented if either fields are empty. This is the script I use:
function checkLoginCredentials() {
var usernameFormValue = $("#usernameForm").val().trim();
var passwordFormValue = $("#passwordForm").val().trim();
var validated;
$("#loginForm").submit(function(event){
if (usernameFormValue === "" || passwordFormValue === "") {
$("span").html("Enter a username or password");
validated = false
} else {
validated = true;
}
return validated;
});
}
However, I noticed that once the script runs and form submission is prevented, the user can no longer make an attempt to log in again. The only alternative I can think of is to have ALL validations done by my login servlet and utility classes. Is there a way around this or must validations of invalid entries like empty strings be done by my Java Classes?
The issue here is how you are assigning the validation code. You have a checkLoginCredentials and when you call it you read the form values. And than you add a form submission. You should add the reading of the textbox values inside of the submit method, not outside.
$("#loginForm").submit(function(event){
var usernameFormValue = $("#usernameForm").val().trim(),
passwordFormValue = $("#passwordForm").val().trim(),
validated;
if (usernameFormValue === "" || passwordFormValue === "") {
$("span").html("Enter a username or password");
validated = false
} else {
validated = true;
}
return validated;
});

Form validation inside a loop in php

I have a commenting system in PHP, in which there is loop to fetch articles. every article has a comment form which needs to be validated for null values.
Now problem is there is no limit to the number of these forms and ID of each form is coming from database. I want to validate each form but without writing the script multiple times.
How can i validate the form field for null value without writing script again & again.
Can i create a loop kind of thing in my script which check the field for null values.
My script is like this -
function validatecomments()
{
nums = ["1", "2", "3", "4"];
text = "commentform"; //form id is like this - commentform1, commentform2, ...
for (var i = 1; i < nums.length; i++) {
text = text + nums[i]; //to create it like form id
if (document.text.comment_emp_id.value=="")
{
alert("Please enter the Employee ID");
document.text.comment_emp_id.focus();
return false;
}
if (document.text.comment.value=="")
{
alert("Please give some Comments");
document.text.comment.focus();
return false;
}
}
}
this is snapshot of the comment form. here are 2 forms with POST button. Problem is i have a number of such forms in a page and i have to check them for null values. I am being forced to write script code multiple times.
Can anyone help me out.
you are not sending correct value to the script. try this
<form name="commentform<?php echo $your_id?>" action="" onSubmit="return validatecomments(this);" method="post">
in your script
function validatecomments(f)
{
if (f.elements['comment_emp_id'].value=="")
{
alert("Please enter the Employee ID");
f.elements['comment_emp_id'].focus();
return false;
}
else if (f.elements['comment'].value=="")
{
alert("Please give some Comments");
f.elements['comment'].focus();
return false;
}
}
May be it helps you.

Categories