Validation not working for dynamically created values - javascript

I have created a form along with dynamically created form fields (name, age). While trying to validate my age field using javascript, only the first record of the age field is validating - the other ones aren't.
The code is:
<script type="text/javascript">
function formValidator(){
var age = document.getElementById('age');
if(isNumeric(age, "Please enter a valid Age")){
return true;
}
return false;
}
function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
HTML code is:
<html>
< body>
<div style="padding-left:70px;">
<input type="button" value="Add Person" onClick="addRow('dataTable')" />
<input type="button" value="Remove Person" onClick="deleteRow('dataTable')" />
</div>
</p>
<table style="padding-left:50px;" id="dataTable" class="form" border="1" >
<tbody>
<tr>
<p>
<td><input type="checkbox" name="chk[]" checked="checked" /></td>
<td>
<label>Name</label>
<input type="text" size="20" name="name[]" id="name" >
</td>
<td>
<label>Age</label>
<input type="text" size="20" name="age[]" id="age" >
</td>
</p>
</tr>
</tbody>
</table>
<div class="clear"></div>
</body>
</html>
Only the first field is validating. How can I validate the dynamically generated fields?

You have duplicate IDs for form element. which is targeting only first element matched with ID. You should rather use same class and target all of them for validation. give class age instead of id and then use:
function formValidator(){
var age = document.getElementsByClassName('age');
for (var i = 0; i< age.length; i++) {
if(!isNumeric(age[i], "Please enter a valid Age")){
return false;
}
}
return true;
}

If You are using dynamic values then pass dynamic ids to the javascript function and then do the validation
For example :
for(i=0;i<results;i++)
{
<input type="text" size="20" name="age[]" id="age"<?php echo i; ?> >
}
And in the javascript function read all the dynamic ids and do the validation.

The bug is in this line. getElementById returns the DOM element and not its value.
var age = document.getElementById('age');
To get the value in the DOM element, you should use the 'value' attribute.
var age = document.getElementById('age').value;
hope that fixes the issue.

You are getting only one element and create it with duplicated ID's. You should get all elements and check them using a loop.
function formValidator(){
var ageEls = document.getElementsByName('age[]'),
valid = true,
i = 0;
while (i < ageEls.length && valid) {
valid = isNumeric(ageEls[i], "Please enter a valid Age");
i++;
}
return valid;
}
JSFiddler example: http://jsfiddle.net/3zsLhe9c/3/

for jquery i have colustion if you use this "jquery.validate.unobtrusive.js" js.
$("#FrmSubmitToAgent").removeData("validator");
$("#FrmSubmitToAgent").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");$("#FrmSubmitToAgent").removeData("validator");
$("#FrmSubmitToAgent").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");

Related

Validating dynamically created input elements

I have a form with dynamically created input elements
<input type='button' value='Add Another Product' id='aprod'>
<table id='page3_inside'>
<tr id='ln1'>
<td>
<label for="product_cat">Product Category</label><br>
<input type='text' class="input product_category" name="product_category[]" style="font-family:verdana; width:150px; border: 1px solid #000000;">
</td>
<td>
<label for="qty">Qty</label><br>
<input type="text" value="" class="input qty" style="width:100px;" name="qty[]" placeholder="Qty" onkeypress="return isNumberKey(event)"/>
</td>
<td>
<label for="unit">Unit</label><br>
<input type='text' class="input unit" style="width:100px;" name="unit[]">
</td>
<td>
<label for="brand">PO Number</label><br>
<input type="text" value="" class="input po" name="po[]" placeholder="PO Number" style='width:150px; height:28px;'/>
</td>
</tr>
</table>
The jQuery for appending elements:
<script>
$('#aprod').on('click', function() {
$('#ln1').clone().appendTo('#page3_inside');
prodnum = prodnum + 1;
$('#conf_prodnum').val(prodnum);
});
</script>
How do I validate each input, since all fields belongs to a class.
In the example I used ID as a selector, but how to do it with class instead?
Thanks.
Try a loop like this:
$('form').submit(function() {
$('form input.input').each(function() {
var valid = 1;
if ($(this).val() == '') {
$(this).addClass('error');
valid = 0;
} else {
$(this).removeClass('error');
}
});
if (valid === 1) {
// submit form
} else {
console.log('error');
return false;
}
});
You might need to change the selector and the condition to check for something more than just empty inputs but those are easy enough.
I'm not quite sure what they are supposed to be since your inputs are in a table in the question, there could be a containing form tag for all I know.
You can also add some styles for inputs with errors to highlight them when form submission has failed:
input.input.error {
border: 1px solid red;
}
I did this using id as selector but how to do it with class as
selector?
$('.conf_prodnum') A dot instead a hash is going to work on classes rather than ids.
Use a loop to visit every element that contains class input and check your inputs like so:
var inputs= $('.input ')
for(x in inputs){
x = inputs[x];
//do whatever you want
}

Validate form input using JavaScript

I am trying to validate 3 form inputs and based on this I want to display either a success page or a failure page. I must do this using JavaScript. I have this so far:
<script src="scripts/formvalidator.js"></script>
<form method = "post" onsubmit = "validateForm()" >
<label><strong>Name:</strong></label>
<br>
<input type="text" name="name" id="name" placeholder="Enter first and last name" />
<br>
<br>
<label><strong>Email:</strong></label>
<br>
<input type="email" name="usremail" placeholder="hello#wavemedia.ie" />
<br>
<br>
<!-- comment box -->
<legend><strong>Your Message</strong></legend>
<textarea name="comments" id="comments" rows="10" cols="50">
</textarea>
<div id="buttons">
<!-- buttons -->
<input type="submit" name="submit" id="submit" value="Send" style="margin-left:100px;">
<input type="reset" name="reset" id="reset" value="Reset" style="margin-left:20px;">
</div>
</form>
My JavaScript file:
// JavaScript Document
//form validation
function validateForm() {
//name check
var name = document.getElementById("name").value;
var nameLength = name.length; //get length of string stored in name
//email - ref http://www.w3schools.com/js/js_form_validation.asp
var email = document.getElementById("usremail").value;
var atpos = email.indexOf("#"); //gets position of the # symbol in the string
var dotpos = email.lastIndexOf("."); //gets position of the last dot in the string
//message - same method as name validation
var message = document.getElementById("comments").value;
var messageLength = message.length;
if (name.length < 3)
{
alert("Make sure all fields are filled in correctly");
return false;
}
else if (atpos < 1 || dotpos<atpos+2 || dotpos+ 2 >= email.length)
{
alert("Make sure all fields are filled in correctly");
return false;
}
else if (messageLength < 20)
{
alert("Make sure all fields are filled in correctly");
return false;
}
else {
return true;
}
}
The problem is when I run the code and submit the form - no matter what I input - nothing happens.
You have defined a function but I cannot see that you are calling it anywhere. You need to call it by changing the corresponding HTML code to this:
<input type="submit" name="submit" id="submit" value="Send" onclick="validateForm()" style="margin-left:100px;">
First, add onClick="function();" to your code.
If you want to get data by name, use getElementsByName("tagname");
Note that the function returns an array. (Because you can add many inputs with the same name, that's why there's Elements).
Working Fiddle [http://jsfiddle.net/pdp44fx4/2/][1]
I couldn't paste it as a link, sorry.

Not Allowing Whitespace With Javascript Validation

I am working on a web form that must be validated on submit. I have a field for a first name that must follow two rules when validated, the name must have at least 3 letters and there can be no spaces between any of the characters. I have gotten it to display an error message when the name is too short, but I can't figure out how to not allow whitespace.
How can I validate this so that there are no spaces between any characters using javascript?
Here is my code so far:
<html>
<head>
<title>Project 5</title>
</head>
<body>
<form name="myForm" id="myForm" onsubmit="return validateForm()">
First Name: <input type="text" id="name"> <br>
Age: <input type="text" id="age"> <br>
Street Address: <input type="text" id="address"> <br>
State: <select>
<option value="la">LA</option>
<option value="tx">TX</option>
<option value="ok">OK</option>
<option value="mi">MI</option>
<option value="az">AZ</option>
</select> <br>
Login Password: <input type="password" id="password"> <br>
<input type="submit" value="Submit"> <br>
</form>
<script type="text/javascript">
function validateForm() {
return checkName();
}
function checkName() {
var x = document.myForm;
var input = x.name.value;
if(input.length < 3) {
alert("Please enter a name with at least 3 letters");
return false;
}
else if(input.length >= 3) {
}
}
</script>
</body>
</html>
there is an option to remove white space of all the text by just using single line of code from Javascript.
text=text.split(' ').join(''); // this will remove all the white space in your text.
I'd recommend using a regex for form input validation. Check examples below:
shouldFailTooShort = 'ts';
shouldFailSpace = 'has space';
shouldPass = 'no-spaces';
validationRule = /^\S{3,}$/;
validationRule.test(shouldFailTooShort) === false;
validationRule.test(shouldFailSpace) === false;
validationRule.test(shouldPass) === true;
Using regular expressions one can have all validation against a field performed in one regular expression check, like presented above. For usability however I'd recommend having one rule for each validation requirement. Then different validation rules can produce different messages and user does not get confused having to read one and always same message.
Have a peek on my favourite regular expression reference.
Edit:
As requested in comment, herein I present my proposal of deploying the solution. I suggest not using alert function in production, but display the message on the page itself, e.g. in a span element.
HTML:
<form name="myForm" id="myForm" onsubmit="return validateForm();">
First Name: <input type="text" id="name" /> <br />
<span id="nameErrMsg" class="error"></span> <br />
<!-- ... all your other stuff ... -->
</form>
<button id="validateTestButton" value="Validate now" onclick="validateForm();">Validate now</button>
JavaScript:
validateForm = function () {
return checkName();
}
function checkName() {
var x = document.myForm;
var input = x.name.value;
var errMsgHolder = document.getElementById('nameErrMsg');
if (input.length < 3) {
errMsgHolder.innerHTML =
'Please enter a name with at least 3 letters';
return false;
} else if (!(/^\S{3,}$/.test(input))) {
errMsgHolder.innerHTML =
'Name cannot contain whitespace';
return false;
} else {
errMsgHolder.innerHTML = '';
return undefined;
}
}
Check live example in jsfiddle.
for (var i=0, len = string.length; i<len; ++i) {
if (string.charAt(i) === ' ') {
alert('Name cannot have spaces!');
break;
}
}

Javascript code is not working second time

I am newbie in javascript. I have two textboxes
<asp:TextBox id="txtbox1" class="txt" runat="server" />
<asp:TextBox id="txtbox2" class="txt" runat="server" />
I am using javascript validation here so that user can't enter NULL value. My javascript code is fine. On button I am using this code.
<asp:Button ID="btn_add" runat="server" OnClientClick="return validate();" OnClick="btn_add_Click" Text="Submit" />
Now, the problem is that when user leaves textbox blank and click on button, error message is shown and after that user corrects his mistakes and again click on the button then button is not working. Nothing happens.
Edit: My javascript code
<script type="text/javascript">
function validate()
{
var error = 0,value,a,q,i;
value = document.getElementsByClassName("txt");
for (i = 0; i < value.length; i++)
{
if (value[i].textContent == '')
{
document.getElementById("errmsg").innerHTML = "TextBox can't be blank";
error = 1;
break;
}
}
if (error == 0)
{ return true }
else { return false}
}
</script>`
I was thrown by your error variable, I would have expected that to fail. The fix is pretty simple. You are using an input and textContent is not a valid attribute as the text is not nested inside the tag (unlike div, p, textarea etc.).
Inputs contain their content in attributes, when a user modifies an input the value is changed and there is the clue. You must access the inputs value.
<script type="text/javascript">
function validate()
{
var error = 0,value,a,q,i;
value = document.getElementsByClassName("txt");
for (i = 0; i < value.length; i++)
{
if (value[i].value == '')
{
document.getElementById("errmsg").innerHTML = "TextBox can't be blank";
error = 1;
break;
}
}
if (error == 0)
{ return true }
else { return false}
}
</script>`
<form action="form_action.php" method="get">
<div id="errmsg"></div>
<div>
<label>First name</label>
<input class="txt" type="text" name="fname" value="" />
<input type="submit" onclick="return validate()" value="Submit" />
</div>
</form>
If you were to bring this piece of code on a bit I would opt for not using the inline function assignment and as mentioned in other comments, use a required flag, then on DOMready check the form for required fields.
Then you can deal with them as you wish, onSubmit, onChange. It will provide you with a bit more flexibility.
ps. You have got to tell me what this does... var error = 1,value,a,q,i
I soved this when user moved out of text box.I through the error.
<form name="forms.sample" novalidate>
<md-input-container class="md-block" flex-gt-sm>
<label>Name:</label>
<input ng-focus="focus=true" ng-blur="focus=false" style="width:400px;" class="form-control" name="Name" type="text" data-ng-model="Name" ng-pattern="SomePattern" required placeholder="enter the Name here" />
<div ng-messages for="forms.sample.Name.$error" ng-if="!focus">
<div ng-if='forms.sample.Name.$touched' ng-message="required">This is required.</div>
<div ng-if='forms.sample.Name.$touched' ng-message="pattern">Enter a valid domain name</div>
</div>
</md-input-container>
</form>

How do I enable cancel button with form validation?

I'm using the frmvalidator javascript found here for my code.
I had to create a custom validation because I'm validating two input fields with the same id (I'm using an array). The validation is working, the problem now though is when I click the cancel button, the validation still takes effect meaning I can't close the dialog box unless I fill in all fields.
Here's my code:
<form name="UpdateIndustry" action="addIndustry.jsp" method="get">
<table align="center">
<c:forEach var="row" items="${paramValues.industries}">
<jsp:setProperty property="tableId" name="bean" value="${row}"/>
<c:set var="ctr" value="${ctr + 1}"/>
<input type="hidden" name="hello" value="${row}"/>
<tr><th>INDUSTRY NAME</th>
<td><div id='UpdateIndustry_industryName_errorloc' style="color:red;"></div>
<input type="text" name="industryName" size=40 value="${bean.thisIndustry.INDUSTRYNAME}"/></td></tr>
</c:forEach>
<input type="hidden" name="finalCount" value="${ctr}"/>
<tr><td style="text-align:center" colspan="3">
<input type=submit name="submit" value="Update Industry" onclick="btnUpdate_click()"/>
<input type=submit name="submit" value="Cancel" onclick="btnCancel_click()"/></td></tr>
</table>
</form>
and the script:
<script language="JavaScript">
var frmvalidator = new Validator("UpdateIndustry");
frmvalidator.EnableOnPageErrorDisplay();
frmvalidator.EnableMsgsTogether();
function btnUpdate_click(){
frmvalidator.setAddnlValidationFunction(FinalValidator); }
function btnCancel_click(){
frmvalidator.clearAllValidations();
window.close(); }
</script>
and here's the FinalValidator function, where the validation happens.
function FinalValidator()
{
var myForm = document.forms["UpdateIndustry"];
if (myForm.industryName.length > 0) {
for(var i=0; i <= myForm.industryName.length; i++)
{
if(myForm.industryName[i].value.length == 0)
{
sfm_show_error_msg('Please enter industry name.', myForm.industryName[i]);
return false;
}
}
}
return true;
}
How can I get the cancel button to work? Thanks in advance for the help! :)
$(document).ready(function () {
$("#YourButtonID").click(function () {
error = false;
$(".span1").remove();
if ($("#YourTextBoxID").val() == "") {
$("#YourTextBoxID").after("<span class='span1'>Write Your Error</span>");
error = true;
}
});
});
Try this.

Categories