Are there any very Simple JQuery Validation? - javascript

Hi I'm looking to add some simple validation to a form.
There are 2 textboxes which the user is expected to enter only numbers and it must be greater than zero. The jquery code is in it's own file (the form consists of html / jquery / php). The first number is for 'previous age' and the second number is for 'current age'. For example, if the user enters '0' in either textbox, an alert or message box should appear informing them that they need to enter a number greater than zero. Anything other than a number greater than zero entered into the textbox should result in the alert message.
As a side note, the .php file is used only for the calculation/math once the user has cleared the requirements of the form.
If someone could provide a clear and concise example, it would much appreciated. I've tried to find a suitable example via google searching, however nothing seemed to fit. Also I'm trying to avoid using a validator plugin, which seemed to be the go to answer when googling the question.
I have my reasons and will be more than happy to explain if needed.
Thank-you,
Charles

if you take away the aspect of your question, validation is fairly basic. All jquery would be used for is to make selecting specific dom elements easier
$(function() {
$('form').submit(function() {
return checkFormIsValid();
});
$('#field1').keyup(function() {
checkField(this.id);
});
$('#field2').keyup(function() {
checkField(this.id);
});
});
function checkFormIsValid()
{
return checkField('field1') && checkField('field2');
}
function checkField(fieldId)
{
var val = $('#'+fieldId).val();
// validation logic
if(isValid) {
return true;
} else {
alert(fieldId+ ' is not valid');
return false;
}
}
This basic validation will be triggered on each field, as well as when the user submits the form.

As Ben Rowe suggest you can use that code, but in checkField(fieldId) function you have to validate that input data should be integer only in that case you can use these codes to vaildate that.
Regex to validet input data

var isEmail_re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
function isEmail(s) {
return String(s).search(isEmail_re) != -1;
}
function isBlank(s) {
if (!s || s.length == 0) {
return true;
}
// checks for a non-white space character
// which I think [citation needed] is faster
// than removing all the whitespace and checking
// against an empty string
return !/[^\s]+/.test(s);
}
function SendContactForm() {
var isFormValid = true;
var isEmailOk = isEmail($('#cemail').val());
if (isEmailOk == false) {
$('#emEmail').css('color', 'red');
isFormValid = false;
}
else {
$('#emEmail').css('color', 'black');
}
var isNameOk = isBlank($('#cname').val());
if (isNameOk) {
$('#emName').css('color', 'red');
isFormValid = false;
//alert('!');
}
else {
$('#emName').css('color', 'black');
}
var isSubjectOk = isBlank($('#csubject').val());
if (isSubjectOk) {
$('#emSubject').css('color', 'red');
isFormValid = false;
}
else {
$('#emSubject').css('color', 'black');
}
var isMesageOk = isBlank($('#cmessage').val());
if (isMesageOk) {
$('#emMessage').css('color', 'red');
isFormValid = false;
}
else {
$('#emMessage').css('color', 'black');
}
if (isFormValid) {
$('#contactFormFields').hide("explode", 1000);
$.post("/Home/SendContactForm", { email: $('#cemail').val(),
name: $('#cname').val(),
subject: $('#csubject').val(),
message: $('#cmessage').val()
},
function (data) {
if (data.length > 0) {
// alert(data);
}
});
}
}
<div id="contactFormFields">
<table>
<tr>
<td style="width: 150px;">
E-Mail
</td>
<td>
<input id="cemail" type="text" value="E-mail" name="email" size="25" class="required email" /><em id="emEmail">*</em>
</td>
</tr>
<tr>
<td style="width: 150px;">
Name
</td>
<td>
<input id="cname" name="name" size="25" class="required" maxlength="100" /><em id="emName">*</em>
</td>
</tr>
<tr>
<td style="width: 150px;">
Subject
</td>
<td>
<input id="csubject" name="subject" size="25" class="required" maxlength="200" /><em id="emSubject">*</em>
</td>
</tr>
<tr>
<td style="width: 150px; vertical-align: top;">
Message
</td>
<td>
<textarea id="cmessage" maxlength="1000" name="comment" cols="27" rows="10" class="required"></textarea><em id="emMessage">*</em>
</td>
</tr>
<tr>
<td style="width: 150px;">
</td>
<td>
<input type="submit" value="Send" class="input-btn" onclick="SendContactForm();" style=" width:100px; color: Black;" />
</td>
</tr>
</table>
</div>

maybe your looking for a plug in to validate form fields?
you can give this a try: http://www.vanadiumjs.com/
just add its js file and your ready.
adding a required validation is as simple as adding css like this
<input class=":required" type="text">
to add an integer validation
<input class=":integer" type="text">
and so on. just follow the link for more info.

Related

Button can't be enabled

My button can't be enabled after having 2 inputs in my textbox not sure how to do this. My button is <input id="rand" type="submit" value="submit" disabled> . I think that its because of the disabled that my entire function is not working... but I don't know any other way to enable it
<script>
function validate()
{
var values = document.getElementById("digit").value;
if(values<0)
{
document.getElementById("numbers").innerHTML = "This is not a number, number must be greater or equal to zero"
return false
}
else if (!(typeof +values && values >= 0)|| values.trim() == "")
{
document.getElementById("numbers").innerHTML = "Fill in a number";
return false;
}
else if (values>=0)
{
document.getElementById("numbers").innerHTML = "";
}
var values1 = document.getElementById("digit1").value;
if(values1<0)
{
document.getElementById("numbers1").innerHTML = "This is not a number, number must be greater or equal to zero"
return false
}
else if (!(typeof +values1 && values1 >= 0)|| values1.trim() == "")
{
document.getElementById("numbers1").innerHTML = "Fill in a number";
return false;
}
else if (values >= values1)
{
document.getElementById("numbers1").innerHTML = "Highest number is smaller than lowest number";
return false;
}
else if (values1 > values)
{
document.getElementById("numbers1").innerHTML = "";
}
if((document.getElementById("digit").value>0) && (document.getElementById("digit1").value>0))
{
document.getElementById("rand").removeAttribute('disabled');
}
else
{
document.getElementById("rand").setAttribute('disabled', 'disabled');
}
}
</script>
This is my codes from my
<body>
<table style="border-collapse: collapse" width="100%">
<form action="random" method="get" onSubmit="return validate()">
<tr>
<td>
Lowest number:
<input id="digit" type="text" name="lowestnumber">
<span id="numbers"></span>
<br/>
</td>
</tr>
<tr>
<td>
Highest number:
<input id="digit1" type="text" name="highestnumber">
<span id="numbers1"></span>
</td>
</tr>
<tr>
<td>
<input id="rand" type="submit" value="submit" disabled><br/>
<input id="randno" type="text"><br/>
</td>
</tr>
<tr>
<td>
<input id="guess" type="text"><br/>
<input id="guessbut" type="button" value="" >
</td>
</tr>
<br/>
</form>
</table>
</body>
You're enabling the button the right way, by using removeAttribute('disabled'). Maybe you just made some logic error, so you don't reach the removeAttribute statement. Check it out by using console.log()
I think everything works well, except one "u never call your javascript!!".
your js code is wrapped in validate() function and u never call it so it wont be ran forever.
u can try call it using
onchange="validate()"
in your input
so this what it will look like
<tr>
<td>
Lowest number:
<input id="digit" type="text" name="lowestnumber" onchange="validate()">
<span id="numbers"></span>
<br/>
</td>
</tr>
<tr>
<td>
Highest number:
<input id="digit1" type="text" name="highestnumber" onchange="validate()">
<span id="numbers1"></span>
</td>
</tr>
I am not an experienced coder but from what I am reading here is that you are trying to validate an input form and based on that you then disable/enable an input field.
First it is best when validating an input form using regex validations instead of conditionals. Then as soon as the regex is true then you would have to parseInt() which converts the input string to a number (since all inputs are type of string). Then you can make the comparisons.
I've broken down the validations in three stages for you to understand, I know it is a bit messy code but everything depends on the implementation. First validation checks the input with a regex then the second validation checks if the number with the first field and the third validation checks if there is any message/text. If there is no text then all is good so the Rad input field is enabled.
function firstValidation(valueToTest) {
// Your regex matches positive numbers only
var yourRegex = /^[+]?\d+([.]\d+)?$/;
// Test the regex, if false then return the message
return yourRegex.test(valueToTest) ?
"" :
"<br/>Input a number, the number must be greater or equal to zero";
}
function secondValidation(firstInput, secondInput) {
return parseInt(firstInput) < parseInt(secondInput) ?
"<br>Highest number is smaller than lowest number" :
"";
}
function thirdValidation() {
var randField = document.getElementById("rand");
var highestMessage = document.getElementById("message-highestnumber")
.innerHTML;
var lowestMessage = document.getElementById("message-lowestnumber").innerHTML;
// If highestMessage or LowestMessage have no message then everything is ok
randField.disabled = highestMessage || lowestMessage;
}
function validate(inputField) {
var message = firstValidation(inputField.value);
var lowestNumber = document.getElementById("lowestnumber");
var highestNumber = document.getElementById("highestnumber");
// Is the Input field the highest number? Then make the extra check
if (inputField === highestNumber)
message += secondValidation(highestNumber.value, lowestNumber.value);
// After all the checks display the message nextElementSibling will automatically go to the next element which is a span
inputField.nextElementSibling.innerHTML = message;
thirdValidation();
}
<body>
<table>
<tr>
<td>
Lowest number:
<input id="lowestnumber" type="text" name="lowestnumber" onchange="validate(this)">
<span id="message-lowestnumber"></span>
</tr>
</td>
<tr>
<td>
Highest number:
<input id="highestnumber" type="text" name="highestnumber" onchange="validate(this)">
<span id="message-highestnumber"></span>
</td>
</tr>
<tr>
<td>
Rand
<input id="rand" type="text" name="rand"><br />
<span id="message-rand"></span></td>
</tr>
</table>
</body>
Again I might complicate things but everything is based on what implementation you do.

issue with form validation including input file

I'm having this very simple form to enter user name and choose a file to upload. User name is required but file is not. It's styled and has a function to check file type and size before submitting the form. If you choose a wrong file the function will work and the submit button will be disabled. If you don't choose a file the user name validation won't work. If you click in the text input then blur it will go red but the form will submit.
JSFIDDLE
HTML
<form method="post" class="contact" onsubmit="return validate();" enctype="multipart/form-data">
<table cellspacing="30">
<tr>
<td>
<label id="userlabel">user name</label>
<input type="text" id="user" name="username" onblur="checkUser()"></td>
</tr>
<tr>
<td>
<div id="FileUpload">
<input type="file" size="4" id="BrowserHidden"
onchange="getElementById('FileField').value = getElementById('BrowserHidden').value;" name="pic" />
<div id="BrowserVisible"><input type="text" id="FileField" /></div>
</div>
</td>
</tr>
<tr>
<td><input type="submit" name="send" id="save" value="send" /></td>
</tr>
</table>
</form>
JS
function checkUser(){
var userlen = $("#user").val().length;
if(userlen<4){
$("#userlabel").css("color","rgb(224, 19, 19)");
return false;
}
else{
$("#userlabel").css("color","#000");
return true;
}
}
$("#BrowserHidden").change(function (e) {
var file = this.files[0];
var name = file.name;
var extension = name.substr((name.lastIndexOf('.') + 1));
var str = 'doc,docx,pdf';
if (str.indexOf(extension) > -1) {
console.log('y');
size = file.size;
console.log(size);
if (size > 10000000) {
alert('file size is larger than 10 MB');
$("#save").attr("disabled", "disabled");
return false;
}
else {
$("#save").removeAttr("disabled");
return true;
}
}
else {
alert('file type is not allowed');
$("#save").attr("disabled", "disabled");
return false;
}
});
function validate(){
$.each($('form :input'),function(){
$(this).blur().change();
});
if(!checkUser() ){
return false;
}
else{
return true;
}
}
This is how you can make it working:
change your submit button to normal one and add onclick attribute to it
remove onsubmit attribute from your form tag
change your validate() function to submit form if checkUser() returns true
That's it!
Fiddle
Hope that worked for you!

JavaScript -- not validating for blank fields

I have the following JavaScript function that is not supposed to allow blank fields to be sent to my back end code, but it's doing it anyway. Even if one or both of my fields is empty, this code is sending 2 blank values. (It works just fine if they're both filled in.) It's also not making my error messages appear. Can anyone help me? Here is my JavaScript.
function submitForm() {
var allValid = true;
var name = $("#name").val();
var comment = $("#comment").val();
if (name == null || name.length == 0) {
allValid = false;
$("#nameReq").css("visibility", "block");
} else {
$("#nameReq").css("visibility", "hidden");
}
if (comment == null || comment.length == 0) {
allValid = false;
$("#commentReq").css("display", "block");
} else {
$("#commentReq").css("display", "hidden");
}
if (allValid) {
clearForm();
$.ajax({
type : "post",
url : "writeComment",
data : "name=" + name + "&comment=" + comment,
success : function(response) {
},
error : function(error) {
}
});
document.getElementById('submit').disabled = true;
}
}
function clearForm() {
$("commentForm").reset();
}
Here is my form.
<form:form id="commentForm" method="post">
<table>
<tr>
<td>Name:<span style="display: none" id="nameReq">
<font style="font-weight: bold; color: red; visibility: hidden;">
<c:out value='Name required' /></font></span><br />
<input type="text" id="name" maxlength="30" /></td>
</tr>
<tr>
<td>Comment:<span style="display: none" id="commentReq">
<font style="font-weight: bold; color: red; visibility: hidden;">
<c:out value='Comment required' /></font></span><br />
<textarea id="comment" rows="20" cols="125" /></textarea></td>
</tr>
<tr>
<td><input id="submit" type="submit" value="Submit comment" onClick="submitForm()" /></td>
<td> </td>
</tr>
</table>
</form:form>
Your form will submit regardless of the action in your onclick function because the input button type is submit. If you'd like to only submit using your AJAX call, change the input to type="button".
Even if you'd like to submit without the ajax call, you can still use type="button" and submit the form using $('#commentForm').submit();
Your textarea is both self-terminating and has a closing tag. When I tried to run this, that confused it to the point that the onClick of the button was not run.

How to get my validated JavaScript data into a MySQL database

To my understanding since JavaScript is a browser-side language and MySQL is server side, I need a server-side language that can interact with the browser such as PHP. I've been looking for solutions here and on the web but to no luck.
My question is -- with the code below is there general format on how can send validated information through the PHP to get to a database?
HTML:
<form method="post" name="regForm" onSubmit="return validateRegForm();">
<table align="center" border="1" bordercolor="black" bgcolor="white" cellpadding="5" cellspacing="0" width="50%">
<tr>
<td>
<table align="center" bordercolor="white" border="0" cellpadding="5" cellspacing="0">
<tr>
<td align="center" colspan="2"><strong>Registration</strong></b></td>
</tr>
<tr>
<td colspan="2"><br></td>
</tr>
<tr>
<td align="right" width="20%">E-mail:</td>
<td align="left" width="30%"><input class="largeTextBox" type="text" name="email" maxlength="50" size="30" placeholder=" email"></td>
</tr>
<tr>
<td align="right" width="20%">Username:</td>
<td align="left" width="30%"><input class="largeTextBox" type="text" name="username" maxlength="50" size="30" placeholder=" username"></td>
</tr>
<tr>
<td align="right" width="20%">Password:</td>
<td align="left" width="30%"><input class="largeTextBox" type="password" name="password" maxlength="50" size="30" placeholder=" password"></td>
</tr>
<tr>
<td align="right" width="20%">Confirm Password:</td>
<td align="left" width="30%"><input class="largeTextBox" type="password" name="cpassword" maxlength="50" size="30" placeholder=" confirm password"></td>
</tr>
<tr>
<td align="right" width="20%">First Name:</td>
<td align="left" width="30%"><input class="largeTextBox" type="text" name="firstname" maxlength="50" size="30" placeholder=" first name"></td>
</tr>
<tr>
<td align="right" width="20%">Last Name:</td>
<td align="left" width="30%"><input class="largeTextBox" type="text" name="lastname" maxlength="50" size="30" placeholder=" last name"></td>
</tr>
<tr>
<td align="right" width="20%">Team Name:</td>
<td align="left" width="30%"><input class="largeTextBox" type="text" name="teamname" maxlength="50" size="30" placeholder=" team name"></td>
</tr>
<tr>
<td colspan="2" align="center"><input class="bigButton" type="submit" value="Register"></td>
</tr>
</table>
</td>
</tr>
</table>
</form>
JavaScript:
function validateRegForm()
{
//Validates email address
var a = document.forms["regForm"]["email"].value;
if (a == null || a == "") {
alert("You forgot to enter your Email!");
return false;
} else {
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (a.match(mailformat)) {
document.regForm.email.focus();
} else {
alert("You have entered an invalid Email Address!");
document.regForm.email.focus();
return false;
}
}
//Validates username
var aa = document.forms["regForm"]["username"].value;
if (aa == null || aa == "") {
alert("You forgot to enter your Username!");
document.regForm.username.focus();
return false;
}
re = /^\w+$/;
if (!re.test(regForm.username.value)) {
alert("Your Username must contain only letters, numbers, and underscores!");
document.regForm.username.focus();
return false;
}
if (aa.length < 7) {
alert("Your Username is too short! (8 character min)");
document.regForm.username.focus();
return false;
}
//Validates password & confirm password
if (regForm.password.value != "" && regForm.password.value == regForm.cpassword.value) {
if (regForm.password.value.length < 7) {
alert("Your Password must contain at least 8 characters!");
document.regForm.email.focus();
return false;
}
re = /[0-9]/;
if(!re.test(regForm.password.value)) {
alert("Your Password must contain at least one number (0-9)!");
document.regForm.password.focus();
return false;
}
re = /[a-z]/;
if(!re.test(regForm.password.value)) {
alert("Your Password must contain at least one lowercase letter (a-z)!");
document.regForm.password.focus();
return false;
}
re = /[A-Z]/;
if(!re.test(regForm.password.value)) {
alert("Your Password must contain at least one uppercase letter (A-Z)!");
document.regForm.password.focus();
return false; }
} else {
alert("Please check that you've entered or confirmed your password!");
document.regForm.password.focus();
return false;
}
//Validates first name
var b = document.forms["regForm"]["firstname"].value;
if (b == null || b == "") {
alert('You forgot to enter your First Name!');
return false;
}
//Validates last name
var c = document.forms["regForm"]["lastname"].value;
if (c == null || c == "") {
alert('You forgot to enter your Last Name!');
return false;
}
//Validates team name
var d = document.forms["regForm"]["teamname"].value;
if (d == null || d == "") {
alert('You forgot to enter your Team Name!');
document.regForm.teamname.focus();
return false;
}
re = /^\w+$/;
if (!re.test(regForm.teamname.value)) {
alert("Team Name must contain only letters, numbers, and underscores!");
document.regForm.teamname.focus();
return false;
}
if (d.length < 7) {
alert("Your Team Name is too short! (8 character min)");
document.regForm.teamname.focus();
return false;
}
return true;
}
There are a lot of approaches to your problem.
This one is what I think,
<form method="post" name="regForm" onSubmit="return validateRegForm();">
This part should have an 'action'.
On your form, there should be an
<input type="submit" name="submit" value="Submit"/>
This will invoke that "onSubmit" action in your "form" tag.
Try this out. Maybe these are the things you're missing out.
Cheers!
Client-side validation has a different role than that of the server. While the server's job is to keep out bad guys and make sure your data is clean, client-side validation should have the purpose of making the filling out of forms as least annoying as possible.
Doing good server-side validation is a science in itself. Fortunately, there are frameworks that make it easier to do it properly (Laravel and CodeIgniter are personal favorites), but if you have the commendable aim of learning to do it from scratch, there's plenty out there to read.
Good client-side validation takes advantage of JavaScript's strengths. It's instant and shows the user exactly where the problem is. You've got that down for the most part, except for the fact that the user gets one error at a time and has to click through alerts until they've got it right. There's also some repetition we can get rid of.
We can gather your validation into an array of objects with a name and a regular expression.
var validators = [
{name: 'username', test: /^[\d\w]{8,}$/},
{name: 'email', test: /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/},
{name: 'password', test: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/},
{name: 'cpassword', test: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/},
{name: 'firstname', test: /w+/},
{name: 'lastname', test: /w+/},
{name: 'teamname', test: /[\w+\d+]{8,}/}
];
Next, let's get rid of the alerts and put red error messages right next to their fields. First, the CSS for that:
td.hide{
display: none;
}
td.error {
font-size: .8em;
color: #F00;
padding: 0 0 0 30%;
}
...and in our table, we'll add hidden rows with the error messages already in them, like so. You could get sophisticated and taylor the message to the type of error by modifying the validators array above with custom messages and then coding for it below, but for simplicity I'm going to leave it as one regex per field and hardcode the error into the hidden validation rows. You could also add ajax calls to the server checking whether usernames/emails are already taken, but this should be a good start.
Now we can make one function that iterates through the array whenever the user changes something. This doesn't cost a whole lot and is practically instant.
function validateRegForm(event)
{
var formIsValid = true;
for(var i=0; i < validators.length; i++){
var currentField = document.getElementsByName(validators[i].name)[0];
var validationField = document.getElementById(validators[i].name + "Validation");
//check that this field is valid, as well as the other filled out ones along the way
if(validators[i].name == event.target.name || currentField.value.length > 0){
if(validators[i].test.test(currentField.value)){
validationField.setAttribute("class", "hide");
}else{
validationField.setAttribute("class", "error");
formIsValid = false;
}
//do the passwords match?
if(currentField.name == 'cpassword' || validators[i].name == 'cpassword'){
if(document.getElementsByName('cpassword')[0].value != document.getElementsByName('password')[0].value){
document.getElementById('cpasswordValidation').setAttribute("class", "error");
formIsValid = false;
}
else {
document.getElementById('cpasswordValidation').setAttribute("class", "hide");
}
}
}
}
if(!formIsValid){
event.preventDefault();
}
return formIsValid;
}
Going over the script, we are first assuming the form is valid with var formIsValid. As soon as we hit something that isn't, we change it to false so that at the end, the form doesn't submit. Then we just iterate through and see what's valid. We ignore empty fields unless it's the one the user just changed, so that the user doesn't start with their email and then get red everywhere because it's all blank. Finally, we put in a special condition to compare passwords.
See my Codepen to see it in action.
On the server, you should check for the same things as above and then properly escape & encode it for storage in the database. You should not assume that the form was posted from your registration page. There are ways to check that on the server and reject the user if the request didn't come from your page. Most server-side languages have built-in ways to do this stuff, but a good framework will make it less of a headache.

jQuery button validate part of a form at a time

Sorry if I did not explain my problem clearly.
I have a form with multiple tables for users inputs.
I use next and back buttons to hide and show different tables in order to guide users.
Now the problem is:
How do I use next button to validate current active table inputs? For example, every time a user click next, it will check if all the fields are filled?
Here is a broken DEMO. Thanks for any comments!
HTML
<form method="post" id="form1" action=index.html>
<table>
<H4 align="center" id="id_tab">
| Chemical |
Crop |
Physical |
</H4>
</table><br>
<table class="tab tab_Chemical" border="0">
<tr>
<th><label for="id_wat_hl">Water Column Half life (days):</label></th>
<td><input type="text" name="wat_hl" id="id_wat_hl" /></td>
</tr>
</table>
<table class="tab tab_Crop" border="0" style="display:none">
<tr>
<th><label for="id_zero_height_ref">Zero Height Reference:</label></th>
<td><input type="text" name="zero_height_ref" id="id_zero_height_ref" /></td>
</tr>
</table>
<table class="tab tab_Physical" border="0" style="display:none">
<tr>
<th><label for="id_mas_tras_cof">Mass Transfer Coefficient (m/s):</label></th>
<td><input type="text" name="mas_tras_cof" id="id_mas_tras_cof" /></td>
</tr>
</table>
<table align="center">
<tr>
<td><input class="back" type="button" value="Back" /></td>
<td><input class="next" type="button" value="Next" /></td>
<td><input class="submit" type="submit" value="Submit" /></td>
</tr>
</table>
</form>
JS
$(document).ready(function() {
var tab_pool = ["tab_Chemical", "tab_Crop", "tab_Physical"];
var visible = $(".tab:visible").attr('class').split(" ")[1];
var curr_ind = $.inArray(visible, tab_pool);
$(".submit").hide();
$(".back").hide();
$('.next').click(function() {
if (curr_ind < 2) {
$(".tab:visible").hide();
curr_ind = curr_ind + 1;
$("." + tab_pool[curr_ind]).show();
$(".submit").hide();
$(".back").show();
}
if (curr_ind == 2) {
$(".submit").show();
$(".next").hide();
}
});
$('.back').click(function() {
if (curr_ind > 0) {
$(".tab:visible").hide();
curr_ind = curr_ind - 1;
$("." + tab_pool[curr_ind]).show();
$(".submit").hide();
$(".next").show();
}
if (curr_ind == 0) {
$(".back").hide();
}
});
$(".next").click(function() {
$(".tab tab_Chemical").validate({
rules: {
wat_hl: "required"
}
})
})
$(".next").click(function() {
$(".tab tab_Crop").validate({
rules: {
zero_height_ref: "required"
}
})
})
$(".next").click(function() {
$(".tab tab_Physical").validate({
rules: {
mas_tras_cof: "required"
}
})
})
});
Add validation using the form
var validator = $('form').validate({
ignore: 'input[type="button"],input[type="submit"]',
rules: {
wat_hl: {
required: true
},
zero_height_ref: {
required : true
},
mas_tras_cof: {
required: true
}
}
});
Then in the next handler
$('.next').click(function () {
var tab = $(".tab:visible");
var valid = true;
$('input', tab).each(function(i, v){
valid = validator.element(v) && valid;
});
if(!valid){
return;
}
if (curr_ind < 2) {
$(".tab:visible").hide();
curr_ind = curr_ind + 1;
$("." + tab_pool[curr_ind]).show();
$(".submit").hide();
$(".back").show();
}
if (curr_ind == 2) {
$(".submit").show();
$(".next").hide();
}
});
Demo: Fiddle
Explanation
var valid = true: a flag to keep the state of the tab through the iteration process
$('input', tab).each: Iterate through each inputs element in the current tab
validator.element(v) validate each element in the tab
valid = validator.element(v) && valid: update the state of the tab
What about this ?
var isOpenedTabValid = $(".tab:visible :input").valid();
I have an implementation to get this same result. I have added div elements with role="form" parameter. And then validates elements on each div as it is like a form while the main form is still wrapping around.
<form action="#" id="myForm" role="form" data-toggle="validator" method="post">
<div id="form-step-0" role="form" data-toggle="validator"><!-- Input elemets --></div>
<div id="form-step-1" role="form" data-toggle="validator"><!-- Input elemets --></div>
<div id="form-step-2" role="form" data-toggle="validator"><!-- Input elemets --></div>
</form>
And this jQuery code to check if there is any error in a particular div
var elmForm = $("#form-step-0");
elmForm.validator('validate');
The following code will check if there is any error input raised in a particular div
var elmErr = elmForm.children('.has-error');
if(elmErr && elmErr.length > 0){
// Error elements found, Form validation failed
return false;
}
And when you want to validate the whole form just use the normal code
var elmForm = $("#myForm");
elmForm.validator('validate');
var elmErr = elmForm.find('.has-error');
if(elmErr && elmErr.length > 0){
alert('Oops we still have error in the form');
return false;
}else{
alert('Great! we are ready to submit form');
elmForm.submit();
return false;
}
Here is the source file on GitHub
Here is a Demo implemeation
You are calling the validate method for each table every time the next button is clicked. Instead, you only want to call validate if the table is visible. Since you are already tracking which table should be visible with your curr_ind, I'd suggest using it to know which table to validate and only calling validate for the visible table.

Categories

Resources