Javascript field.setCustomValidity() doesn't set field to valid - javascript

I have an HTML form and using Javascript to validate the form. However, when I use setCustomValidity(), it doesn't seem to work properly. I have to click on the submit button twice to mark the field as invalid, and then when the correct input is entered, the field is not marked as valid again, i.e. the error message keeps repeating.
Here's my HTML:
<form id="data_form" onsubmit="event.preventDefault(); return validateForm();">
<table>
<tr>
<td colspan="2" class="right_align">
<label for="supplier_ref"> Supplier Reference Number: </label>
</td>
<td colspan="2">
<input id="supplier_ref" name="supplier_ref" type="number" required>
</td>
</tr>
<!-- more rows -->
<button id="generate" name="generate" type="submit" onclick=""> Generate Barcode </button>
</table>
</form>
Javascript:
function validateForm() {
var form = document.forms["data_form"];
var emptymsg = "Field must be filled out.";
var supplier_ref = form.elements["supplier_ref"];
var supplier_ref_value = supplier_ref.value.toString();
if (supplier_ref_value == "") {
supplier_ref.setCustomValidity(emptymsg);
return false;
}
if (supplier_ref_value.length != 9){
supplier_ref.setCustomValidity("Number has to be 9 digits long.");
return false;
} else {
supplier_ref.setCustomValidity("");
}
return true;
}
When the length of the Supplier Reference is less than 9 digits, the error message appears, but when I enter the correct length, I still get the same error.
I would appreciate any help.
Thanks in advance

Nvm it only works with addEventListener

Related

Form is not validated before call javascript function

Below is my simple jsp form where i need to validate the whether the branch number is empty before doing the ajax call.
<body>
<div id = "divOrderuserinputContainer">
<table align="center" id="table">
<form id="orderform" onsubmit="return validateForm()" method="POST">
<td class="label">Branch Number:
<input type="text" name="branch" ></input>
</td>
<td>
<input type="submit" value="submit" onclick="addData(); return false;"></input>
</td>
</form>
</table>
</div>
</body>
Below is my javascript
function validateForm(form) {
var x = document.forms["orderform"]["branch"].value;
if (x == "") {
alert("You must select a valid Branch branch");
return false;
}
}
If i remove the return false; in the submit input it does populate alert form the branch input but it still calls the addData(). How to validate the form before call the function addData().
when you click on your submit button, your function addData will be called first and then your validateForm function. If I understood right, you want to validate the form on submission and then call your addData if everything is okay! In this case you can do this:
<body>
<div id = "divOrderuserinputContainer">
<table align="center" id="table">
<form name="orderform" id="orderform" onsubmit="return validateForm();" method="POST">
<td class="label">Branch Number:
<input type="text" name="branch" >
</td>
<td>
<input type="submit" value="submit">
</td>
</form>
</table>
</div>
</body>
and the JS:
function validateForm() {
var x = document.forms["orderform"]["branch"].value;
if (x == "") {
alert("You must select a valid Branch branch");
return;
} else {
addData();
}
}
function addData() {
// di stuff here with your data
alert('Everything is okay do stuff');
}
Make just one function that is called on submit event. Inside that function call another one like your validateForm(). If you discover that something is wrong while validating, call event.preventDefault()/event.returnValue = false or just return false as you already know. Also if you want branch numbers to be numeric, use isNumeric function instead of just checking if it is an empty string.
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function isDataValid(data) {
// your checks...
if (!isNumeric(data.branch)) return false;
return true;
}
function addData() {
var e = event || window.event;
var data = {};
data.branch = document.forms["orderform"]["branch"].value;
// other data
// ...
if(!isDataValid(data)) {
console.log("Data is invalid! The submit will not happen!");
e.preventDefault();
} else {
// remove this else-branch later to make submit happen because the data in this case is valid
console.log("Data is valid! The submit will happen!");
e.preventDefault();
}
}
document.getElementById("orderform").addEventListener('submit', addData, false);
<div id = "divOrderuserinputContainer">
<table align="center" id="table">
<form id="orderform" method="POST">
<td class="label">Branch Number:
<input type="text" name="branch" ></input>
</td>
<td>
<input type="submit" value="submit"></input>
</td>
</form>
</table>
</div>
PS don't forget to handle cross-browserness addEventListener/attachEvent, preventDefault/returnValue = false etc. Also you could collect errors inside isDataValid and show them later to users in case they inserted something incorrectly.

How to properly validate 2 or more fields together in Javascript?

I want to validate 2 fields together using JavaScript code.
What i'm doing is disabling the submit button when user enters invalid data.
Something like this:
Disabled Button when incorrect data is entered
The problem is that when i enter invalid data in field 1 the button is disabled but when i add proper form data in second field the button gets enabled again, i even used global variable but the problem still persists.
Button enabled even if data in first field is wrong
My JavaScript code is :
<script>
var sw=0;
function valqid(qid){
if(isNaN(qid) || parseInt(qid)<0){
alert("Please Enter Valid Question ID!");
document.getElementById("button").disabled = true;
window.sw=1;
}
else{
if(window.sw==0){
document.getElementById("button").disabled = false;
}
}
}
function valans(ans){
if(parseInt(ans)!=0 && parseInt(ans)!=1){
alert("Please Enter Valid Answer!");
document.getElementById("button").disabled = true;
window.sw=1;
}
else{
if(window.sw==0){
document.getElementById("button").disabled = false;
}
}
}
</script>
Here qid and ans are values inputted by user.
Kindly tell me how to make it work properly.
(Validation rules are listed below in image files)
Thanks in advance.
Complete Code HTML is given below:
<html>
<body>
<center>
<form action="add_questions.php" method="POST" name="form4"> <br /> <br />
<table cellspacing="10" cellpadding="10" border="1">
<tr> <th> Question ID </th> <th> Question </th> <th> Answer </th> </tr>
<tr> <td> <input type="text" name="question_id" maxlength="3" minlength="1" onchange="valqid(this.value)" required /> </td> <td> <input type="text" name="question" maxlength="200" minlength="10" id="ques" required /> </td> <td> <input type="text" name="answer" maxlength="1" onchange="valans(this.value)" required /> </td> </tr>
</table> <br /> <br />
<input type="submit" value="Add Question" name="add_question" id="button" />
</form> <br /> <br />
<p> * Enter Question Id, Question & Answer of the question you want to add. </p>
<p> * All three are mandatory fields (cannot be empty). </p>
<p> * Question Id can be 3 numbers (Whole Numbers only) long at most and should be atleast 1 number (character).</p>
<p> * Question can be 200 characters long at most and should be atleast 10 characters. </p>
<p> * Answer field should be '1' for 'True' & '0' for 'False'.</p>
<p> * Question Id must be unique.</p>
<script>
var sw=0;
function valqid(qid){
if(isNaN(qid) || parseInt(qid)<0){
alert("Please Enter Valid Question ID!");
document.getElementById("button").disabled = true;
window.sw=1;
}
else{
if(window.sw==0){
document.getElementById("button").disabled = false;
}
}
}
function valans(ans){
if(parseInt(ans)!=0 && parseInt(ans)!=1){
alert("Please Enter Valid Answer!");
document.getElementById("button").disabled = true;
window.sw=1;
}
else{
if(window.sw==0){
document.getElementById("button").disabled = false;
}
}
}
</script>
</body>
</html> ;
You can use this simple way
<script>
function valqid(qid){
if(isNaN(qid) || parseInt(qid)<0){
alert("Please Enter Valid Question ID!");
document.getElementById("button").disabled = true;
}
else if(parseInt(ans)!=0 && parseInt(ans)!=1){
alert("Please Enter Valid Answer!");
document.getElementById("button").disabled = true;
}
else{
document.getElementById("button").disabled = false;
}
}
</script>

How do I validate radiobuttons using a javascript function?

I have a computing assignment to do.
I've done most I'm just stuck on this task:
"Add a set of radio buttons to the form to accept a level of entry such as
GCSE, AS or A2. Write a function that displays the level of entry to the user
in an alert box so that the level can be confirmed or rejected."
I have done the Radio Buttons I just don't know how to do the second part with the Alertbox and function.
So far my code looks like this:
<html>
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value == "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value == "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
result = false;
}
if (document.ExamEntry.examno.value == "") {
msg += "You must enter your Examination Number \n";
document.ExamEntry.examno.focus();
document.getElementById('examinationno').style.color = "red";
result = false;
}
if (msg=="") {
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<! Main HTML content begins >
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr></tr>
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="examinationno">Examination Number</td>
<td><input type="text" name="examno" maxlength="4" /></td>
</tr>
<tr>
<td><input type="radio" name="Level" value="GCSE">GCSE</td>
</tr>
<tr>
<td><input type="radio" name="Level" value="AS">AS</td>
</tr>
<tr>
<td><input type="radio" name="Level" value="A2">A2</td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" onClick="return validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
All you have to do is add the value of the radio button to the message like this:
msg += "Level of Entry: "+document.ExamEntry.Level.value;
Here is a fiddle demo you can try
EDIT #1: Though it has been said to use an alert box, that wouldn't actually allow the user to confirm or reject, for that, you could use confirm instead:
if (confirm("Click OK to confirm your Level of Entry or Cancel if you would like to correct it"))
return true;
else
return false;
In my example, I added it only in case the rest of the form validation was successful: http://jsfiddle.net/Qd8sk/2/
EDIT #2: Following our conversation, I updated the jsfiddle you created. It is much more simple than what you provided.
Here is yours: http://jsfiddle.net/Kjxmn/
Here is mine: http://jsfiddle.net/Kjxmn/2/
Several things I changed:
-1. Added return in front of the function name in onchange - looks like otherwise it would still submit even on return false.
-2. Corrected the form name that you called radioform this time, not Exam Entry.
-3. Got rid of the slightly cumbersome check of the selected value using if (document.radioform.level.value == '') instead.
-4. Added the confirm check.
EDIT #3: Looks like firefox doesn't like the usage of document.ExamEntry.Level.value for radio buttons, so instead I created a quick workaround that would loop through the elements of document.ExamEntry.Level and find the one that is 'selected' ('checked' actually - even though it's a radio button, the js code is still called 'checked').
Have a look at the updated fiddle: http://jsfiddle.net/Qd8sk/3/
function confirm () {
var alerttxt = "Are you sure you want to choose",
value = document.ExamEntry.name.value;
alerttxt += value;
alert(alerttxt);
}
The value variable holds the value the user chose in the radio button, you just want to append that to a message you make up and display that whole txt in an alert

Row Validation with Jquery Validation plugin

I have a series of forms that correspond to likert questions:
<form class="indicator-form" request="post">
<fieldset>
<label class="top-label">
Enter the number of <strong>category 1</strong> staff that answered each level of importance on a 5-point likert-field scale for the question:<br/>
<em>Question 1?</em>
</label>
<table>
<tr class="likert">
<td>
<label for="cat1_a">Very Unimportant</label>
<input id="cat1_a" name="cat1_a" class="likert-field" type="text" />
</td>
<td>
<label for="cat1_b">Unimportant</label>
<input id="cat1_b" name="cat1_b" class="likert-field" type="text" />
</td>
<td>
<label for="cat1_c">Neutral</label>
<input id="cat1_c" name="cat1_c" class="likert-field" type="text" />
</td>
<td>
<label for="cat1_d">Important</label>
<input id="cat1_d" name="cat1_d" class="likert-field" type="text" />
</td>
<td>
<label for="cat1_e">Very Important</label>
<input id="cat1_e" name="cat1_e" class="likert-field" type="text" />
</td>
</tr>
</table>
</fieldset>
<fieldset>
<label class="top-label">
Enter the number of <strong>category 2</strong> staff that answered each level of importance on a 5-point likert-field scale for the question:<br/>
<em>Question 2?</em>
</label>
<table>
<tr class="likert">
<td>
<label for="cat2_a">Very Unimportant</label>
<input id="cat2_a" name="cat2_a" class="likert-field" type="text" />
</td>
<td>
<label for="cat2_b">Unimportant</label>
<input id="cat2_b" name="cat2_b" class="likert-field" type="text" />
</td>
<td>
<label for="cat2_c">Neutral</label>
<input id="cat2_c" name="cat2_c" class="likert-field" type="text" />
</td>
<td>
<label for="cat2_d">Important</label>
<input id="cat2_d" name="cat2_d" class="likert-field" type="text" />
</td>
<td>
<label for="cat2_e">Very Important</label>
<input id="cat2_e" name="cat2_e" class="likert-field" type="text" />
</td>
</tr>
</table>
</fieldset>
<input type="submit" value="Submit Data"/>
</form>
I want to validate each table row so that:
If there is no data in the row, no validation is applied (i.e. a user
can submit an empty row)
If there is any data in the row, all fields must be filled out.
My JS:
// Likert Row Validation
jQuery.validator.addMethod('likert', function(value, element) {
var $inputs = $(element).closest('tr.likert').find('.likert-field:filled');
if (0 < $inputs.length && $inputs.length < 5 && !($(element).val())){
return false;
} else {
return true;
}
}, 'Partially completed rows are not allowed');
// Likert Fields
jQuery.validator.addClassRules('likert-field', {
likert: true
});
var validator = $('.indicator-form').validate({
errorPlacement: function(error, element){
errorPos = element;
errorClass = 'alert-arrow-center';
error.insertAfter(errorPos).addClass(errorClass);
}
});
On the face of it, this validation works - but if you start playing around with it, it becomes clear that the rule is only applied to the fields that are blank when the submit button is clicked.
How can I make it so that the validation rule applies to all fields unless there is no data at all?
JSfiddle here: http://jsfiddle.net/6RtcJ/1/
It's behaving strangely because validation is only triggered for one field at a time (unless you click the submit). If you blank out data in one field, then only the one field is re-evaluated. This is why you have messages lingering around on other fields.
It's not ideal, but you can force the whole form to re-validate on every keyup and blur event using the valid() method like this...
$('input').on('blur keyup', function() {
$('.indicator-form').valid();
});
Your demo: http://jsfiddle.net/6RtcJ/20/
Same idea, but only triggered by blur event...
http://jsfiddle.net/6RtcJ/21/
Quote OP:
"... it becomes clear that the rule is only applied to the fields that are blank when the submit button is clicked."
If you're expecting validation messages to appear on a field even after the same field passes validation, then that's not how this plugin works.
There are ways to group messages together using the groups option, which may help you a bit. You can also use the errorPlacement callback to position the one message for the whole row.
The way the groups option works is that it will group all error messages for several fields into one message... so only after all fields in the group pass validation, the single message will go away.
I've set the onkeyup option to false in this example since all fields now share the same message.
groups option demo: http://jsfiddle.net/6RtcJ/22/
ok , i got your meaning.
there are some solution here.
1.remove the rules on this form when all input not insert any word.
2.add the rules ,if one of the input had data.
you should do a check before validation?
Try this:
$(document).ready(function(){
$('.indicator-form').validate({
onfocusout:false,
submitHandler: function (form) {
alert('Form Submited');
return false;
}
});
// Likert Fields
/*
$('.likert-field').each(function(){
$(this).rules('add',{
required: true,
messages: {
required: "Partially completed rows are not allowed",
},
});
});
*/
$("input[type='submit']").click(function(){
$("tr.likert").each(function(){
var $inputs = $(this).find('.likert-field:filled');
if (0 < $inputs.length && $inputs.length < 5) {
$(this).children('td').children('.likert-field').each(function() {
$(this).rules('add',{
required: true,
});
});
} else {
$(this).children('td').children('.likert-field').each(function() {
$(this).rules('remove');
});
}
});
});
});

javascript checkbox validation checking

I have problem with my checkbox validation on my Tip Area Soccer Game. So if the user likes to tip a game, he must have to use 2 inputs field and the confirmation checkbock. But if the user uses 2 inputs fields and "more than one" confirmation checkbox, then he must get an alert error message. Because the right combination consists from "2 input fields + confimration checkbox" Here, in my screenshot you see the right combination for the green submit button:
And in the second screenshot you see the error combination:
I don't have any idea of how to code the alert for the error message on the display if the user uses the second combination.
Here's my Javascript code:
function chkAddTip(){
var inputs = document.getElementById('AddTip').getElementsByTagName('input');
// boolean flag
var foundValid = false;
// early exit the loop if at least one valid bet has been found
for (var i = 0; i < inputs.length && !foundValid; i += 3){
if (inputs[i].type !== "submit" && (inputs[i].value && inputs[i + 1].value && inputs[i + 2].checked)) {
// set the flag to true when a valid bet is found
foundValid = true;
}
}
// determine the return value depending on the flag
if (foundValid) {
return true;
}
else {
alert("Bitte deinen Tipp und die Bestättigung abgeben.")
inputs[0].focus();
return false;
}
And here my form code:
<form action="Ctipservlet" id="AddTip" onsubmit="return chkAddTip()" method="POST">
<div id="inhalt"><h1>Tip Area</h1>
<table>
<tbody>
<tr>
<th>Playdate</th>
<th>Playtime</th>
<th>Games</th>
<th>Your Tip</th>
<th>Confirmation</th>
</tr>
<tr>
<td>21.07.</td>
<td>19:30 Uhr</td>
<td>Schalke - Bayern</td>
<td><input style="width:30px!important; text-align: center;" type="text" name="team_a0" maxlength="2" size="2">:<input style="width:30px!important; text-align: center;" type="text" name="team_b0" maxlength="2" size="2"></td>
<td><input type="checkbox" name="check0"></td>
</tr>
<tr>
<td>22.07.</td>
<td>20:30 Uhr</td>
<td>Dortmund - Leverkusen</td>
<td><input style="width:30px!important; text-align: center;" type="text" name="team_a1" maxlength="2" size="2">:<input style="width:30px!important; text-align: center;" type="text" name="team_b1" maxlength="2" size="2"></td>
<td><input type="checkbox" name="check1"></td>
</tr>
<tr>
<td>23.07.</td>
<td>15:30 Uhr</td>
<td>Wolfsburg - Nürnberg</td>
<td><input style="width:30px!important; text-align: center;" type="text" name="team_a2" maxlength="2" size="2">:<input style="width:30px!important; text-align: center;" type="text" name="team_b2" maxlength="2" size="2"></td>
<td><input type="checkbox" name="check2"></td>
</tr>
</tbody>
</table>
<input class="button_green" type="submit" name="tip" value="Submit Tip">
<input class="button_blue" onclick="this.form.onsubmit = null" type="submit" name="back" value="Back">
</div>
</form>
I hope someone have idea for this checking
We talked in chat, looked at this. Below is my solution but first... this is badly structured. You are doing validation and form submission in one step. I would break it up in to more then one. It just makes debugging/extension easier in the long run. I would validate inputs first. Save into object. Send to submit function. Then submit to DB. This right now is trying to do all that in one function. Anyway....
The problem is the loop for checking if there are inputs. When it finds the first true result it will call a submit and exit the function.
That's why you can input 2 fields, a checkbox and other checkboxes and foundValid is true.
My fix was to check for invalid input first. Have an outer boolean as an error. If it passes it submits. The only issue with it right now is empty fields will return a true condition and submit. Check the JS Fiddle http://jsfiddle.net/Komsomol/EDdUU/4/
var error = false;
var results = [];
function chkAddTip() {
var inputs = document.getElementById('AddTip').getElementsByTagName('input');
console.log(inputs);
// early exit the loop if at least one valid bet has been found
for (var i = 0; i < inputs.length; i += 3) {
if (!inputs[i].value && !inputs[i + 1].value && inputs[i + 2].checked) {
console.log("inputs inputed wrong!");
error = true;
} else {
results.push(inputs[i].value,inputs[i + 1].value,inputs[i + 2].checked);
}
}
submit();
}
function submit(){
console.log(results, error);
if(error == true){
alert("error in inputs");
} else {
alert("posting to server");
}
}

Categories

Resources