Validate only visible fields in a form - javascript

I am validating one form. when required fields are not entered it will return alert.its working fine.
Now I have hide some form fields by adding ng-class,when I click submit I don't want to validate hidden fields I want to validate only those fields which are not having hidden class.
These are my inputs:
<section ng-class="{'hidden':true}">
<input class="required" ng-model="currentData.name" />
</section>
<section ng-class="{'hidden':true}">
<input class="required" ng-model="currentData.id"/>
</section>
<section>
<input class="required" type="text" ng-model='currentData.age'/>
</section>
<section ng-class="{'hidden':true}">
<input class="required" ng-model='currentData.gender'/>
</section>
<section>
<input class="required" ng-model='currentData.description'/>
</section>
Here am validating my fields :
$form.find('input.required').each(function() {
var $this = $(this)
if ($this.val().trim() == '') {
alert("enter required fields")
}
})
I have added `:visible` its working good.But that wont be a proper solution I guess.Because if there are multiple tabs which is not having `hidden class`means, it will validate only current tab user currently viewing.
$form.find('input.required:visible').each(function() {
var $this = $(this)
if ($this.val().trim() == '') {
alert("enter required fields")
}
})
Any other suggestions?

$('form').find('input.required').parent('*:not(".hidden")').each(function() {
var $this = $(this)
if ($this.val().trim() == '') {
alert("enter required fields")
}
})
assuming $('form') is <form></form>,
otherwise it should be something like
$('#form') for <div id="form"></div>

Got solution:
$form.find('section').not(".hidden").closest('input.required').each(function() {})
I just changed my elements order.

Related

How to perform validation in multiple groups of inputs according to condition

I am creating a set of textboxes dynamically while pressing (+) button, by cloning the following HTML template:
<div id= "other_leaders" class="controls form-input">
<input type="text" name="other_leader_fname[]" class="input_bottom other_leader_fname" id="other_leader_fname" placeholder="First Name" value="'.$val[0].'" />
<input type="text" name="other_leader_lname[]" class="input_bottom other_leader_lname" id="other_leader_lname" placeholder="Last Name" value="'.$val[1].'" />
<input type="text" name="other_leader_email[]" class="other_leader_email" id="other_leader_email" placeholder="Email Address" value="'.$val[2].'" />
<input type="text" name="other_leader_org[]" class="other_leader_org" id="other_leader_org" placeholder="Organisation/College" value="'.$val[3].'" />
<span class="remove btn"><i class="icon-minus"></i></span>
</div>
I am able to do single textbox validation by following code:
$("input[name*='other_leader_fname']").each(function(){
if($(this).val()=="" || !RegExpression.test($(this).val()))
{
$(this).addClass('custom-error')
fnameflag = 0;
}
});
Now my question is how to do empty validation for all four textboxes, if any one textbox field is filled by the user in that particular textbox group.
for example: if i enter values in the <div> with id other_leader_fname, then it should perform empty validation for other three textboxes of this particular group.
how can i do it?
Try this , You can apply your validation rules to all the text box in the div by using following code:
$("#other_leaders :input[type='text']").each(function(){
if($(this).val()=="" || !RegExpression.test($(this).val()))
{
$(this).addClass('custom-error')
fnameflag = 0;
}
});
As you have just one element so there is no need to have a loop over it:
var $othLeader = $("input[name*='other_leader_fname']");
if($othLeader.val()=="" || !RegExpression.test($othLeader.val())){
$(this).addClass('custom-error');
fnameflag = 0;
}
And if you have form then you can validate this in your form's submit function.
You can iterate over the .controls using the each() and check for filled inputs in each group using filter for performing the validation as follows:
$('.controls').each(function(){
var $inputs = $(this).find('input');
var filled = $inputs.filter(function(){
return this.value != "";
});
if(filled.length){
$inputs.each(function(){
if($(this).val()=="" || !RegExpression.test($(this).val()))
{
$(this).addClass('custom-error')
fnameflag = 0;
}
})
}
});
Demo
side note: since the above is a template for dynamically generated content, You should remove the id and use class instead since id should be unique in a document.

How to autopopulate div class form

I have an Autoresponder email form on my page.
Below is part of the code of that form, for the email to be entered by customer:
<div id = "af-form-45" class = "af-form" >
<div id = "af-body-45" class = "af-body af-standards" >
<div class = "af-element" >
<label class = "previewLabel" for = "awf_field-57" > </label>
<div class="af-textWrap">
<input class="text" id="awf_field-57" type="text" name="email" value="Form 555" tabindex="500" onfocus=" if (this.value == 'Form 555') { this.value = ''; }" onblur="if (this.value == '') { this.value='Form 555';} " / >
</div>
<div class="af-clear"> </div>
</div>
</div>
</div>
</div>
The prepopulated email value in that form is 'Form 555'. Meaning that is someone lands on the page and sees the form, it already has the value of 'Form 555'
What I need to do is to pre-populate the field not with 'Form 555', but with certain value, which I get from running a Javascript in my header (that Javascript is long, so I'm not including it here).
But for example, if I put the below code on the page, it will return a certain email address (which I need to be prepopulated in the form).
<script type="text/javascript">formData.display("email")</script>
So I need to do the same, but inside that div class form - this email address to be added instead of 'Form 555' prepopulated value
Thanks!
You can set val throu
$("#awf_field").val(formData.display("email"));
Pretty simple, is there something else you are struggling with?
Change
<script type="text/javascript">formData.display("email")</script>
to
<script type="text/javascript">
$('#awf_field').val(formData.display("email"))
</script>

Form login button enabled after password field has focus

hello guys I have a login page with two inputs username and password and one button. I want to put a class on that button after password field has first character filled in. How can I do that , Thank's. If is possible to do that only with css will be awesome, or a small script to add a class on that button.
<form>
Username <input type="text" name="first" id="first" /><br/><br/>
Password <input type="text" name="last" id="last" />
<br/>
</form>
<input class="crbl" type="submit" name="last" id="last" value="login button" />
css
/*Normal State*/
.crbl{
margin-top:10px;
border:1px solid #555555;
border-radius:5px;
}
/*after password field has one character filled in state*/
.class{
???
}
fiddle:
http://jsfiddle.net/uGudk/16/
You can use toggleClass and keyup methods.
// caching the object for avoiding unnecessary DOM traversing.
var $login = $('.crbl');
$('#last').keyup(function(){
$login.toggleClass('className', this.value.length > 0);
});
http://jsfiddle.net/5eYN5/
Note that IDs must be unique.
You can do that using javascript. FIrst thing you need to put on password input the following event
Password <input type="text" name="last" id="last" onkeyup="myFunction(this);"/>
Then you define the javascript function:
function myFunction(element) {
if (element.value != '') {
document.getElementById('last').attr('class','password-1');
} else {
document.getElementById('last').attr('class','password-0');
}
}
You may try like this demo
jQuery(document).ready(function(){
jQuery('#last').keyup(function(event){
var password_length =jQuery("#last").val().length;
if(password_length >= 1){
jQuery("#last_button").addClass('someclass');
}
else
{
jQuery("#last_button").removeClass('someclass');
}
});
});
This is the best way to handle the entire input, with the "on()" Jquery method.
Use the very first parent
<form id="former">
Username <input type="text" name="first" id="first" /><br/><br/>
Password <input type="text" name="last" id="last" />
<br/>
</form>
<input class="crbl" type="submit" name="last" id="last_btn" value="login button" />
Then in Jquery
$("#former").on('keydown, keyup, keypress','#last',function(e){
var value = $(this).val();
if ( value.length > 0 ) {
$("#last_btn").addClass('class'):
}else{
$("#last_btn").removeClass('class');
}
});
With "on" method you can handle many event of the input as you can see...
make sure your ID is unique.. since you have two IDs with the same name in fiddle.. i changed the password id to 'password'...
use keyup() to check the key pressed.. and addClass() to add the class..
try this
$('#password').keyup(function(){
if($(this).val()==''){
$('#last').removeClass('newclassname'); //if empty remove the class
}else{
$('#last').addClass('newclassname'); // not not empty add
}
});
fiddle here
<script type="text/javascript">
$('#YourTextBoxId').keyup(function (e) {
if ($(this).val().length == 1) {
$(this).toggleClass("YourNewClassName");
}
else if ($(this).val().length == 0) {
$(this).toggleClass("YourOldClassName");
}
})
</script>
Test this:
http://jsfiddle.net/uGudk/33/
Please consider using unique id for all form elements, and use unique input name also.
$(document).ready(function(){
$("input[name=last]").keydown(function () {
if($(this).val().length > 0){
$(this).attr("class", "class");
//or change the submit button
$("input[type=submit]").attr("class", "class");
//or if you want to enable it if originally disbaled
$("input[type=submit]").removeAttr("disabled");
}
});
});

jQuery submit a form

html code
<div id="signup">
<form id="suform" method="POST" action="roma/roma">
<p>
<label>Frist Name</label>
<input type="text" id="sufName"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Last Name</label>
<input type="text" id="sulName"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Email</label>
<input type="text" id="suEmail"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Mobile Number</label>
<input type="text" id="suMNumber"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Password</label>
<input type="password" id="suPassword"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Re Password</label>
<input type="password" id="suRePassword"/>
<span class="errorMessage"></span>
</p>
<p>
<input type="submit" class="button" value="sign up"/>
</p>
</form>
</div>
it is just six input fields to make a sign up page
and this is the jQuery code to ensure that there is no input field empty, and if there is no input field empty I want to submit the form.
jQuery code
$(document).ready(function(){
$('#suform').on('submit', function(e){
e.preventDefault();
var errorCount = 0;
$('span.errorMessage').text(''); // reset all error mesaage
$('input').each(function(){
var $this = $(this);
if($this.val() === ''){
var error = 'Please fill ' + $this.prev('label').text(); // take the input field from label
$this.next('span').text(error);
errorCount = errorCount + 1;
}
});
if(errorCount === 0){
$(this).submit(); // submit form if no error
}
});
});
The code ensure that there is no input field empty, it found an empty one then an error message will appear, else should submit, but the submit doesn't work.
code
Try using $(this)[0].submit();. Using $(this) refers to the jQuery object reference to the form. I don't know what jQuery's submit() method actually does, but it clearly doesn't submit the form. Using $(this)[0] refers to the actual DOM element, which will use the standard DOM submit method, which is what you're looking for.
I'm sure you know this already, but you should use server and client side validation, because some users don't have JS and some users will purposely tamper with your form. Just a quick "Don't forget"!
Check out the jQuery validation plugin. For this you add a class = "required" for any input field that is required, and just call validation on it:
$('form').validation({
// any options you want
});
It will also do handy things like displaying error messages, doing conditional validation, etc.
You can remove e.preventDefault() and use return insead:
$('form').on('submit', function(e){
var errorCount = 0;
$('span.errorMessage').text('');
$('input').each(function(){
var $this = $(this);
if($this.val() === ''){
var error = 'Please fill ' + $this.prev('label').text();
$this.next('span').text(error);
errorCount = errorCount + 1;
}
});
return errorCount === 0;
});
DEMO: http://jsfiddle.net/h9njC/27/
$('form').on('submit',function(e){
var errorCount = 0;
$('span.errorMessage').text('');
$('input').each(function(){
var $this = $(this);
if($this.val() === ''){
var error = 'Please fill ' + $this.prev('label').text();
$this.next('span').text(error);
errorCount = errorCount + 1;
}
});
if(errorCount === 0){
alert('done'); // just an alert to notice when everything OK [remove it]
$this.submit(); // submit the form on success
} else e.preventDefault(); // halt the submission on default
});
DEMO

How to validate radio and array before submitting form?

I need to validate two things on this form:
1. There are two radio buttons:
• OPTION 1 - On click function hides mm/dd/yyyy fields for OPTION 2
• OPTION 2 - On click function shows mm/dd/yyyy fields which aren't required.
2. Zip code field - Need to validate an array of acceptable zip codes.
I've got this form MOSTLY working aside from a few issues:
1. If you click submit without checking or filling out anything it replaces some of the text on the page with the word "Invalid" and vice versa when valid info has been filled in.
2. It does not go to the next page if valid info has been submitted.
3. It only validates the zipcode field and does not require the radio buttons.
Any help would be greatly appreciated! Thanks!
Test page here: http://circleatseven.com/testing/jquery/zipcodevalidation/
If i have you understand you search for this:
I dont have write a Message with "invalid", i give an alert.
In your HTML add "onsubmit" to your form-Tag:
<form method="post" action="success.php" id="step1" onsubmit="checkdata();">
and add a submit-Button to your form or trigger on your pseudo-submit-button .submit() with jQuery.
In your Javascript you add following function:
function checkdata() {
if ($(":radio:checked").length < 1) {
alert('Please choose an Option!');
return false;
}
zipCodeOk = false;
zipCodes = new Array(75001, 75002, 75006); //Your Zip-Codes
for (var i = 0; i <= zipCodes.length; i++) {
if ($('#enterZip').val() == zipCodes[i]) {
zipCodeOk = true;
break;
}
}
if (!zipCodeOk) {alert('Please enter a valid Zip-Code!');return false;}
}
A friend helped me out.. We ended up using the Jquery validate plugin - here's what we came up with:
<script type="text/javascript">
$(document).ready(function(){
jQuery.validator.addMethod("validZip", function(value) {
var zips=['12345', '23456', '34567', '45678', '56789', '67890', '78901', '89012', '90123', '01234'];
if ($.inArray(value,zips) > -1) {
return true;
} else {
return false;
}
}, "invalid zip");
$("#step1").validate({
rules: {
currentServiceStatus: "required",
enterZip: { validZip : true }
}
});
$('.moveInDates').hide();
$(":radio:eq(0)").click(function(){
$('.moveInDates').hide();
});
$(":radio:eq(1)").click(function(){
$('.moveInDates').show();
});
});
</script>
And here's the html:
<form method="post" action="success.php" id="step1">
<h1>CHOOSE *</h1>
<input name="currentServiceStatus" type="radio" value="Switch Me" /> OPTION 1
<br/>
<input name="currentServiceStatus" type="radio" value="Move-In" /> OPTION 2 (reveals more fields on click)
<div id="dateInputs" class="moveInDates">
<h2>Move-In Date (not required)</h2>
<p><span class="mmddyyyy"><input name="moveInDateMonth" type="text" class="text" id="moveInDateMonth" /> / <input name="moveInDateDay" type="text" class="text" id="moveInDateDay" /> / <input name="moveInDateYear" type="text" class="text" id="moveInDateYear" /></span>
</div>
<hr/>
<h1>ZIP CODE *</h1>
<p>Enter one of the following acceptable Zip Codes:</p>
<p>12345, 23456, 34567, 45678, 56789, 67890, 78901, 89012, 90123, 01234</p>
<input name="enterZip" type="text" class="text" id="enterZip" />
<hr/>
<input type="image" id="submitButton" src="http://circleatseven.com/testing/jquery/zipcodevalidation/library/images/btn_submit.jpg" />
<p><em>* Required</em></p>
</ul>

Categories