How to validate a simple web form - javascript

Im working on a small form and using js to validate if the fields are empty or not. I have a span class next to the name field "name" "email".
For the "name" field, i have a span class called "error".
For the "email" field, i have another span class called "error2".
what can i do to only use one class to display the "error message", because of course i will have more field and I don't want to keep adding more classes. error3, error4
HTML:
<form action="#i" name="myForm" onsubmit="return(validate());">
Name: <span id="error"></span><br>
<input type="text" name="Name" /><br><br>
EMail: <span id="error2"></span><br>
<input type="text" name="EMail" /><br> <br>
<input type="submit" value="Submit" /> <br>
</form>
JS:
function validate()
{
var t = 0;
if( document.myForm.Name.value == "" )
{
document.getElementById('error').innerHTML = "<br>Empty";
t = 1;
}
if( document.myForm.EMail.value == "" )
{
document.getElementById('error2').innerHTML = "<br>Empty";
t = 1;
}
if(t == 1)
{
return false;
}
else
return true;
}

Instead of giving the spans the attribute of Id, use classes instead. So for example, you can define ALL your spans as follows:
<span class="error"> ... </span>
Then, in your validate function, you can obtain these spans through:
document.getElementsByClassName('error');
Keep in mind though, this returns an array, which would actually be perfect for your function. This way, you can write a basic for-loop to go through each span and make sure each field is filled in correctly.

Related

User must enter a value if a checkbox is checked

I have the following input field and a checkbox:-
<input id="ClientManagerApproval_e565da24-d454-4537-b902-771a37689e9d_MultiChoiceOption_0" type="checkbox">
<input type="text" value="" id="ProjectManHoursUsed_becead30-410d-42de-872e-c12ad4c322b2_$NumberField" title="Man Hours Used" size="11" class="ms-input" style="ime-mode : inactive">
now what i am trying to do inside jQuery, if that if the checkbox is checked then the user must enter a value inside the input field, i tried this but it did not work (the alert will never show!)
if ($("[id^=ProjectManHoursUsed_]").value === "" && $("[id^=ClientManagerApproval_]").is(':checked'))
{
alert("Please enter Man Hour Used before setting the stage to Closure approval");
result = false;
}
JQuery has its own function for getting values. Replace
$("[id^=ProjectManHoursUsed_]").value
by
$("[id^=ProjectManHoursUsed_]").val()
See here:
$("button").on("click", function(){
if ($("[id^=ProjectManHoursUsed_]").val() === "" && $("[id^=ClientManagerApproval_]").is(':checked')){
alert("Please enter Man Hour Used before setting the stage to Closure approval");
result = false;
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="ClientManagerApproval_e565da24-d454-4537-b902-771a37689e9d_MultiChoiceOption_0" type="checkbox">
<input type="text" value="" id="ProjectManHoursUsed_becead30-410d-42de-872e-c12ad4c322b2_$NumberField" title="Man Hours Used" size="11" class="ms-input" style="ime-mode : inactive">
<button>submit</button>
You can achieve the result you're looking by using the following code snippet without needing any jQuery at all:
if (document.querySelector('.chkbx').checked) { // I'd recommend using class instead of id, here chkbx if the class attr of the checkbox input -> class="chkbx"
alert("Please enter Man Hour Used before setting the stage to Closure approval");
result = false;
}
You are trying to check if value is empty when value is undefined. If you want to make sure if there's any value, you can use ! operator. You should use === to make sure for empty string over null.
I just changed your code from $("[id^=ProjectManHoursUsed_]").value === "" to !$("[id^=ProjectManHoursUsed_]").value and it's working fine.
function testMe() {
let result = true
if (!$("[id^=ProjectManHoursUsed_]").val() && $("[id^=ClientManagerApproval_]").is(':checked'))
{
alert("Please enter Man Hour Used before setting the stage to Closure approval");
result = false;
}
return result
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onSubmit="return testMe();">
<input id="ClientManagerApproval_e565da24-d454-4537-b902-771a37689e9d_MultiChoiceOption_0" type="checkbox"/>
<input type="text" value="" id="ProjectManHoursUsed_becead30-410d-42de-872e-c12ad4c322b2_$NumberField" title="Man Hours Used" size="11" class="ms-input" style="ime-mode : inactive"/>
<input type='submit' value="Click"/>
</form>

Compare input text with person name belongs to only one input number id

Im trying to write a validation for 2 groups of fields. I have 6 inputs, 3 for text name and 3 more for id number... the validation should do this "if input name="RE_SignedByID" has an input type name="RE_SignedByName", then other inputs name="RE_SignedByID", should NOT contain the same name="RE_SignedByName" More easy explanation... one ID number should have only one Person Name (Id number is unique for one person name). What can I use for that? Should I map() all the inputs?
Those are my inputs:
<div id="signedBy" class="clearfix">
<label>Signer, person ID & name</label>
<span id="signedByID" class="ids half">
<input type="text" name="RE_SignedByID" placeholder="personID, person1" data-validate="" tabindex="101" required>
<input type="text" name="RE_SignedByID" placeholder="personID, person2" data-validate="" tabindex="103">
<input type="text" name="RE_SignedByID" placeholder="personID, person3" data-validate="" tabindex="105">
</span>
<span class="names half">
<input type="text" name="RE_SignedByName" placeholder="name, person1" tabindex="102" required>
<input type="text" name="RE_SignedByName" placeholder="name, person2" tabindex="104">
<input type="text" name="RE_SignedByName" placeholder="name, person3" tabindex="106">
</span>
</div>
I guess it should also be an "on change" function? or can I make the validation on click? Some ideas...? Im actually compleatley lost here...
Thanks in advance!!!
Maybe use different class names for all 3 of them to make them unique?
<input class="name1">
<input class="name2">
<input class="name3">
I'm not sure what you mean but if you want to make the input types unique and not call them all when you write class="names half", then you should give them all unique class names.
So from my understanding you don't want multiple fields to have the same value.
My approach would be this:
let inputTimeout = null; //set an empty timeout object
let vars = [null, null, null, null]; // create an array containing as many nulls as you have inputs
$('.nameInput').on('keyup', function(){
let self = $(this);
clearTimeout(inputTimeout); //clear the timeout
inputTimeout = setTimeout(function(){ //set a timeout to check whether there is a dupe after the user has stopped typing
if (vars.indexOf(self.val()) == -1){ //check if the vals array contains the newly entered string
vars[self.attr('data-inputnum')] = self.val(); //insert the value into the array
}else{
//handle duplicates here
}
}, 500); //500ms is a sensible value for end of user input, change it if users complain that your app is too fast/slow
});
You then just have to edit your HTML a bit so that all name inputs have a class in common (i used .nameInput) and have a data-inputnum attr.
This would look something like this:
<input type="text" name="RE_SignedByName" placeholder="name, person1" tabindex="102" class='nameInput' data-whichinput='0'/>
<input type="text" name="RE_SignedByName" placeholder="name, person2" tabindex="103" class='nameInput' data-whichinput='1'/>
<!--and so on-->
Of course, never rely on JavaScript verification alone, always also check inside your backend. However this would be out of scope for this answer.
Hi Thanks all for the help, made me realize a couple of things till I got the answer. This is my working code:
var valSignedID = $("[name=SignedByID]").map(function() {
return this.value.trim();
}).get();
var valOwnersID = $("[name=OwnersID]").map(function() {
return this.value.trim();
}).get();
valSignedID.sort();
valOwnersID.sort();
for (var i = 0; i < valSignedID.length - 1; i++) {
if (valSignedID[i] == valSignedID[i + 1] && valSignedID[i] != "") {
alert(" You can not have duplicated signers ID's");
return false;
// break;
}
}
for (var i = 0; i < valSingedName.length; i++) {
if (valSingedName[i] == valSingedName[i + 1] && valSingedName[i] != "") {
alert(valSingedName[i] + " should not have different ID");
//return false;
}
}

Javascript or jQuery fill data based on value

I am currently trying to get a solution in order to simplify the login for my staff. Ideally I am looking for a js or jQuery script that pre-fills 2 input fields based upon the data they enter.
E.g. the main field should be: Enter token
IF the token equals 123 then fill input1 and input2 with certain amount of data, while if the token is 456 fill it with other data - if no token matches then do not fill any data. I know this is very unsecure but since it's something running only locally it would work for my specific needs.
<style>.hidden {display: none !important;}</style>
<form>
<input id="token" type="text">
<input class="hidden" id="input1" type="text">
<input class="hidden" id="input2" type="password">
<input type="submit">
</form>
Some advice would be greatly appreciated, thank you
Its pretty simple, You can get the desired result by using the conditional statement like if else.
here is the solution for your problem.
var token=$('#token').val();
if(token==123)
{
$('#input1').val('value1'); //set the value which you want to place here
$('#input2').val('value2'); //set the value which you want to place here
}
else if(token==456)
{
$('#input1').val('value1'); //set the value which you want to place here
$('#input2').val('value2'); //set the value which you want to place here
}
else {
$('#input1').val('');
$('#input1').val('');
}
You're basically wanting to add an input event listener to #token and set the values of the hidden inputs based on the value entered.
Something like this should suffice...
// make sure this script goes AFTER the HTML
// A map of token to values
const secrets = {
123: {
input1: 'input1 123',
input2: 'input2 123'
},
456: {
input1: 'input1 456',
input2: 'input2 456'
}
}
const input1 = document.getElementById('input1')
const input2 = document.getElementById('input2')
document.getElementById('token').addEventListener('input', e => {
const token = e.target.value
// get the values or if the token doesn't exist, sensible defaults
const secret = secrets[token] || {
input1: '',
input2: ''
}
input1.value = secret.input1
input2.value = secret.input2
}, false)
<form>
<input id="token" type="text" placeholder="Enter token">
<input class="hidden" id="input1" type="text">
<input class="hidden" id="input2" type="password">
<input type="submit">
</form>
Try the jquery code given below:
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script type="text/javascript">
$('#token').keyup(function() {
if($(this).val() == 123) {
$('#input1').val('1'); //assign the value you want
$('#input2').val('1'); //assign the value you want
} else if($(this).val() == 456) {
$('#input1').val('2'); //assign the value you want
$('#input2').val('2'); //assign the value you want
} else {
$('#input1').val('');
$('#input2').val('');
}
});
</script>

Validating a form when either a "select" OR "input" is required

I have a page containing multiple forms, all different, and when one is submitted I use the function below to gather all the inputs from that form with the class "required" and check for empty values:
function validateForm(form) {
var inputs = form.getElementsByTagName('input');
var selects = form.getElementsByTagName('select');
var errors = 0;
for (var i = 0; i < inputs.length; i++) {
if(inputs[i].classList.contains('required')) {
if(inputs[i].value === "") {
inputs[i].classList.add("warning");
errors++;
} else {
inputs[i].classList.remove("warning");
}
}
}
if(errors) {
return false;
} else {
return true;
}
}
If it finds an empty value, it adds the class "warning" which just gives the input a red border, then returns false so the form doesn't get submitted.
Here's where I'm running into trouble: Some forms contain a <select> and a text input, ONE of which must be filled in, but not both, as well as various other text inputs. I'm trying to figure out how to modify the above function to handle this.
Let's say the form is for adding a new product. The select is dynamically populated with existing product "categories" and the text input is for if the user wants to create a new category. Here's a simplified version of the form:
<form method = "post" onsubmit = "return validateForm(this)">
<div class = "form-group">
<label>Product Name</label>
<input class = "form-control required" type = "text" name = "product" />
</div>
<div class = "form-group">
<select class = "form-control required" id = "category" name = "category[]">
<option value = "">Select Existing Category</option>
<option value = "Shirts">Shirts</option>
<option value = "Shoes">Shoes</option>
<option value = "Pants">Pants</option>
</select>
</div>
<div class = "form-group">
<label>Create New Category</label>
<input class = "form-control required" type = "text" name = "category[]" />
</div>
<div class = "form-group">
<input class = "btn btn-primary" type = "submit" value = "Submit" />
</div>
</form>
Since I'm using a for loop to go through the inputs - the select and the input are not going to have the same index, so I can't do something like this:
if((selects[i].value === "" && inputs[i].value === "") || (selects[i].value !== "" && inputs[i].value !== "")) {
// add the warning class to both
}
I feel the answer lies somewhere in using the name attribute, i.e. compare selects.name and inputs.name, but how do I get around the differing index in the loop? And also, it should only make this comparison when the select is encountered anyway. It doesn't necessarily exist, depending on the form.
Basically, I need to modify my function to do this:
I. Gather all inputs and selects (if any - some forms will not) from a submitted form
II. Make sure none of the inputs with the "required" class are blank (unless there's a corresponding select, in which case see III below)
III. If there's a select, find the text input with the same "name" (not a requirement to have the same name, but I assume this is the right way to do it). One of them, but not both, must have a value. If both are blank, or both have a value, they should get the "warning" class;
Any help anyone can offer will be greatly appreciated!
Here's a function that do exactly what you want and can handle any form you want, as long as they have the same HTML structure.
Notes:
I recommend avoiding inline event listeners as much as you can, in
the snippet below I used addEventListener method to attach submit
event to all the forms in the document, you can change this to just
some specific forms if you want.
Instead of only adding a border to the required elements, I suggest
you also add some text to tell what the problem is.
// getting all forms in the page you can also get specific forms based on their class-name
var forms = document.getElementsByTagName('form'),
l = forms.length,
i = 0;
// adding submit submit event listener to the referenced forms
for(; i < l; i++) {
forms[i].addEventListener('submit', validateForm);
}
function validateForm(e) {
var els = this.querySelectorAll('input.required'),
len = els.length,
err = false,
c = 0,
inpName = '';
// checking if the form has a select, if so, allow only the select or the input to be filled
var isSelect = this.getElementsByTagName('select');
if(isSelect[0] !== undefined && isSelect[0] !== null) {
var inp = isSelect[0].parentNode.nextElementSibling.querySelector('input.required');
inpName = inp.name;
if((isSelect[0].value == '' && inp.value.trim().length === 0) || (isSelect[0].value != '' && inp.value.trim().length > 0)) {
err = true;
isSelect[0].classList.add("warning");
inp.classList.add("warning");
} else {
isSelect[0].classList.remove("warning");
inp.classList.remove("warning");
}
}
// iterate through the rest of the inputs and check for empty one, thus trimming them before checking
for(; c < len; c++) {
if(els[c].name !== inpName) {
if(els[c].value.trim() == '') {
err = true;
els[c].classList.add("warning");
} else {
els[c].classList.remove("warning");
}
}
}
// based on the error variable, either submit the form or cancel submission
(!err) ? this.submit():e.preventDefault();
}
.warning {
border: 2px solid red;
}
<form method="post">
<div class="form-group">
<label>Product Name</label>
<input class="form-control required" type="text" name="product" />
</div>
<div class="form-group">
<select class="form-control required" id="category" name="category[]">
<option value="">Select Existing Category</option>
<option value="Shirts">Shirts</option>
<option value="Shoes">Shoes</option>
<option value="Pants">Pants</option>
</select>
</div>
<div class="form-group">
<label>Create New Category</label>
<input class="form-control required" type="text" name="category[]" />
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" value="Submit" />
</div>
</form>
Hope I pushed you further.
You may get a message saying: "The custom error module does not
recognize this error." when you successfully submit the form from the
snippet above, that due to StackOverflow's restrictions as they
don't allow/server side code (StackOverflow doesn't let the form to
be submitted).

Javascript validation nightmare

I'm trying to get my "username" and "password" fields to verify that there is information in them before submitting the form.
What should I need to add to my HTML and to my JavaScript to have them work! If you want to suggest a new JavaScript, please do!
HTML:
<form action="validateForm.html" id="registrationForm">
<label for="username" id="usernameLabel">* Username:</label>
<input type="text" name="username" id="username" value="Your username" />
<div id="usernameError" style="display:none"></div>
<br/><br/>
<label for="password" id="passwordLabel">* Password:</label>
<input type="password" name="password" id="password" />
<div id="passwordError" style="display:none"></div>
<br/><br/>
<input type="submit" value="Submit Form" id="submit" />
</form>
JavaScript
function validateForm()
{
if(!document.getElementByName("username"))
{
alert("Username field is required!");
}
if(!document.forms[0].username){
alert("Username field is required!");
}
if(!document.for (var i = username.length - 1; i >= 0; i--) {
alert("Username field is required!")
};)
}
One way would be getting your input by id and then validate its value
HTML
<input type="text" id="username" />
<input type="password" id="password" />
JS
function validateForm()
{
if(!document.getElementById("username").value) // true if input value is null, undefined or ""
{
alert("Username field is required!");
}
else if(!document.getElementById("password").value)
{
alert("Username field is required!");
}
}
(i strongly recommend you to use more attractive ways of giving users feedback than JS alerts)
I think all of those checks are incorrect in some for, let's start with the first one:
if(!document.getElementByName("username"))
{
alert("Username field is required!");
}
It's document.getElementsByName() (notice the plural)
The function returns an array of elements, so you'd still need to check for the value of the one you want (probably 0)
This is going to be true always as the field exist, you need to check the value in the input, but right now you are just checking the existence of the input.
Next one is similar:
if(!document.forms[0].username){
alert("Username field is required!");
}
You are checking the existence of the field, not its value
This type of selection is not recommended, you should be using a document.getElementBy... better.
And finally:
if(!document.for (var i = username.length - 1; i >= 0; i--) {
alert("Username field is required!")
};)
It looks like you tried to make a for loop but copy-pasted from above and got this mess... not even going to try to understand why the loop.
Recommendations:
Use the attribute id and read the fields using document.getElementById()
To check if a field has content, check its value: .value
Add an event handler for the form (onsubmit="validateForm()")
Make the form validator return false if one of the fields is incorrect (otherwise the form will be sent even with the incorrect fields)
Optionally: use the HTML5 required attribute.
So the function would look like:
function validateForm()
{
if(document.getElementById("username").value == "")
{
alert("Username field is required!");
return false;
}
// check the other fields
// .....
}
May I suggest something like this instead:
HTML:
<form action="validateForm.html" onSubmit="return validateForm(this)">
<label for="username" name="usernameLabel">* Username:</label>
<input type="text" name="username" id="username" placeholder="Your username" />
<div id="usernameError" style="display:none"></div>
<br/><br/>
<label for="password" name="passwordLabel">* Password:</label>
<input type="password" name="password" />
<div id="passwordError" style="display:none"></div>
<br/><br/>
<input type="submit" value="Submit Form" />
</form>
JS:
function isEmpty (field) {
return field.value === "";
}
function validateForm (form) {
// assume the form to be valid
var isValid = true;
// create a variable to store any errors
var errors = "";
// check if the username is empty
if(isEmpty(form.username)) {
// our assumption is incorrect, the form is invalid
isValid = false;
// append the error message to the string
errors += "Username field is required!\n";
}
if (isEmpty(form.password)) {
isValid = false;
errors += "Password field is required!\n";
}
// display the errors if the form is invalid
if (!isValid) {
alert(errors);
}
return isValid;
}
This way, you are passing the form directly to the validateForm function and can easily access each field using their name properties. You can then check if they're empty by determining what their value contains.
If you need to get the DOM by it name means it will returns an Array so you need to get it by
if(!document.getElementsByName("username")[0].value == ""){
//do ur stuff
}
or
if(!document.getElementById("username").value == ""){
//do ur stuff
}

Categories

Resources