Adding and removing rules to JQuery Validator based on user input? - javascript

Would like to disable the validation rules for certain fields depending on user input.
Working with jquery validator plugin, is that possible at all? The JSfiddle is here: http://jsfiddle.net/webhelpla/3eQam/
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#form").validate();
});
</script>
</head>
<body>
<form id="form" method="get" action="">
<p>
<label>Validate all
<input type="radio" name="fields_to_validate" value="all" id="fields_to_validate_0">
</label>
</p>
<p>
<label> Validate name only
<input type="radio" name="fields_to_validate" value="name" id="fields_to_validate_1">
</label>
</p>
<p>
<label for="cname">Name</label>
*<input id="cname" name="name" size="25" class="required" minlength="2" />
</p>
<p>
<label for="cemail">E-Mail</label>
*<input id="cemail" name="email" size="25" class="required email" />
</p>
<p>
<input class ="submit" type="submit" value="Submit"/></p></form>
</body>
</html>

What youre looking for is a condition argument to the field
I believe it goes like this, remove the hard coded required classes from your input elements, name the two radio buttons denoting your required fields as different names like name_only and:
$('form').validate({
rules:
name:{
    required: function() {
return $("input:radio[name='nameonly']:checked").val() == 'yes';
}
}
});
so its not determining what should be required by direct user inputs dynamically, its the inputs becoming required based on conditional inputs

Related

how to do html form vaildation in jquery

i am using html and jquery to do some form vaildations
for ex if user click on a field and doesn't enter any thing, than he clicks on different field... i want to turn field border to red. this way user will know that he can not skip this field...
also when user clicks on button submit, than i also want to do this same, if field is empty than turn border to red
below is what i have so far, is there a better way to do this? bbc it seem like i am repeating alot of same code
on up side it does work fine, so guess i can just keep on repeating code
note i have like 20+ fields so jquery function will be long
forgot to tell that i am using asp fields:
<asp:TextBox ID="FirstNameCTB" ClientIDMode="Static" class="input form-control input-md" runat="server"></asp:TextBox>
javascript code:
<script type="text/javascript">
$(function () {
$('#FirstNameCTB').blur('input', function () {
if ($('#<%=FirstNameCTB.ClientID%>').val().trim() == '')
$('#<%=FirstNameCTB.ClientID%>').css('border-color', 'red');
else
$('#<%=FirstNameCTB.ClientID%>').css('border-color', '');
});
$('#LastNameCTB').blur('input', function () {
if ($('#<%=LastNameCTB.ClientID%>').val().trim() == '')
$('#<%=LastNameCTB.ClientID%>').css('border-color', 'red');
else
$('#<%=LastNameCTB.ClientID%>').css('border-color', '');
});
$('.CHECKOUTLBC').click(function () {
if ($('#<%=FirstNameCTB.ClientID%>').val().trim() == '') {
$('#<%=FirstNameCTB.ClientID%>').css('border-color', 'red');
return false; // dont go to server side
} else {
$('#<%=FirstNameCTB.ClientID%>').css('border-color', '');
}
if ($('#<%=LastNameCTB.ClientID%>').val().trim() == '') {
$('#<%=LastNameCTB.ClientID%>').css('border-color', 'red');
return false; // dont go to server side
} else {
$('#<%=LastNameCTB.ClientID%>').css('border-color', '');
}
});
});
</script>
https://jqueryvalidation.org/ can be your solution.
Also here's the examples.
https://jqueryvalidation.org/files/demo/
This plugin has, red border, submit control etc.
Also this plugin will be good.
http://www.formvalidator.net/#reg-form
$.validate({
modules : 'location, date, security, file',
onModulesLoaded : function() {
$('#country').suggestCountry();
}
});
// Restrict presentation length
$('#presentation').restrictLength( $('#pres-max-length') );
<form action="" id="registration-form">
<p>
E-mail
<input name="email" data-validation="email">
</p>
<p>
User name
<input name="user" data-validation="length alphanumeric"
data-validation-length="3-12"
data-validation-error-msg="User name has to be an alphanumeric value (3-12 chars)">
</p>
<p>
Password
<input name="pass_confirmation" data-validation="strength"
data-validation-strength="2">
</p>
<p>
Repeat password
<input name="pass" data-validation="confirmation">
</p>
<p>
Birth date
<input name="birth" data-validation="birthdate"
data-validation-help="yyyy-mm-dd">
</p>
<p>
Country
<input name="country" id="country" data-validation="country">
</p>
<p>
Profile image
<input name="image" type="file" data-validation="mime size required"
data-validation-allowing="jpg, png"
data-validation-max-size="300kb"
data-validation-error-msg-required="No image selected">
</p>
<p>
User Presentation (<span id="pres-max-length">100</span> characters left)
<textarea name="presentation" id="presentation"></textarea>
</p>
<p>
<input type="checkbox" data-validation="required"
data-validation-error-msg="You have to agree to our terms">
I agree to the terms of service
</p>
<p>
<input type="submit" value="Validate">
<input type="reset" value="Reset form">
</p>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script>
Assuming all your form inputs are called input, you could loop through them and apply the function with something similar to this.
var inputs = document.getElementsByTagName('input');
for(n = 0; n < inputs.length; n++){
$(function () {
inputs[n].blur('input', function () {
if (inputs[n].val().trim() == '')
inputs[n].css('border-color', 'red');
else
inputs[n].css('border-color', '');
});
});
}
couple things:
issue maybe be that javascript is beeing run before the controls
you should not mix core javascript with jquery libary
you do not need loop when using blur, on, click, etc jquery functions
keeping all those above things in mind, below is a better solutions. works for me
$(function () {
$(".input").blur(function () {
if ($(this).val().trim() == '')
$(this).css('border-color', 'red');
else
$(this).css('border-color', '');
});
});
Have a look at this example below.
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<legend>Please provide your name, email address (won't be published) and a comment</legend>
<p>
<label for="cname">Name (required, at least 2 characters)</label>
<input id="cname" name="name" minlength="2" type="text" required>
</p>
<p>
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="email" name="email" required>
</p>
<p>
<label for="curl">URL (optional)</label>
<input id="curl" type="url" name="url">
</p>
<p>
<label for="ccomment">Your comment (required)</label>
<textarea id="ccomment" name="comment" required></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</fieldset>
</form>
<script>
$("#commentForm").validate();
</script>
Have a look at this example:

clear certain text using jquery

I face problem with reset value to empty with jquery when click radio button.
<form id="my-form">
<div>
<label for="name">Name</label>
<input type="text" id="name" name="name" value="123" />
</div>
<div>
<label for="ID">ID NO</label>
<input type="text" id="ID" name="ID" value="NO21034" />
</div>
<fieldset>
<legend>Option</legend>
<label for="clearID">clearID</label> <input type="radio" id="clearID" name="opt" checked />
<label for="clearName">clearName</label> <input type="radio" id="clearName" name="opt" />
</fieldset>
</form>
<script type="text/javascript">
$(document).ready(function()
{
$('#clearname').on('click', function()
{
$('#my-form').find('input:text').val('');
});
});
</script>
now if my radio button click clearName,it will automatic clear the value of name and id.
is it having another code can replace find('input:text') ?I want to clear either one value(name or id),not both.
Clear each field using corresponding id..
<script type="text/javascript">
$(document).ready(function()
{
$('#clearname').on('click', function()
{
$('#ID').val('');//it clears the value of element having id='ID'
$('#name').val('');//it clears the value of element having id='name'
});
});
</script>
use javascript reset method
$('#clearname').on('click', function()
{
$("#my-form")[0].reset()
// or
$("#my-form").get(0).reset()
});

Unwanted autofill on html form

I am (for the first time) making a signin/register form for a website. For the line in the register form where I ask the user to provide their email address it provides an autofill option, which is fine. The problem is that it also fills in the line below which is where I will get the user to retype the email address to verify it. I have tried using autocomplete="off" but that does not seem to have an affect.
I managed to figure out that if the second email input does not have the word "email" in it the autocomplete does not affect this line. Still tho, autocomplete="off" had no affect and I don't know why. Ideally I would like to have email in the name of this line off code to make it easier to read and similar issues may come up in the future.
Any ideas why this is happening? here is my code:
<!DOCTYPE html>
<html5>
<head>
<title>Login page</title>
</head>
<body>
<h1>Login or Register</1h>
<p></p>
<div id="logindOrRegdiv">
<input type="button" value="Login" id="login">
<input type="button" value="Register" id="register">
</div>
<div id="logindiv">
<form name="login" autocomplete="on">
Username<input type="text" name="userid"/><br>
Password<input type="password" name="pswrd"/><br>
<input type="button" onclick="check(this.form)" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
<script language="javascript">
function check(form) { /*function to check userid & password*/
/*the following code checkes whether the entered userid and password are matching*/
if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd") {
window.open('target.html')/*opens the target page while Id & password matches*/
}
else {
alert("Error Password or Username")/*displays error message*/
}
}
</script>
</div>
<div id="registerdiv">
<form name="register" autocomplete="on">
First Name<input type="text" name="firstname"/><br>
Middle Name<input type="text" name="middlename"/><br>
Last Name<input type="text" name="lastname"/><br>
D.O.B.<input type="text" name="dob"/><br>
Email Address<input type="email" name="email"/><br>
Re-Type<input type="email" name="email2" autocomplete="off"/><br>
Password<input type="password" name="password"/><br>
Re-Type<input type="password" name="password2"/><br>
</form>
</div>
<script src="jquery-1.11.2.js"></script>
<script src="app.js"></script>
</body>
</html5>
The autocomplete="off" attrbute has bugs in most major browsers.
http://caniuse.com/#feat=input-autocomplete-onoff
The workaround is to give the name attribute a random value each time the page is loaded. For example name="email-jirbcea".

Form validation is not fired in the before send call back function using jquery validation plugin

I am very new to jQuery.I have done a simple task that validation form data using jQuery validation plugin.
I have created a simple form
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="js/jquery.validate.js"></script>
<script src="js/form-validate.js"></script>
</head>
<body>
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<legend>Please provide your name, email address (won't be published) and a comment</legend>
<p>
<label for="cname">Name (required, at least 2 characters)</label>
<input id="cname" name="name" minlength="2" type="text" class =" requiredFieldCheck ">
</p>
<p>
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="email" name="email" required>
</p>
<p>
<label for="curl">URL (optional)</label>
<input id="curl" type="url" name="url">
</p>
<p>
<label for="ccomment">Your comment (required)</label>
<textarea id="ccomment" name="comment" required></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</fieldset>
</form>
<script>
//$("#commentForm").validate();
$(function(){
$('#commentForm').ajaxForm({
beforeSend:function(){
alert('before send');
$('#commentForm').validate();
},
success:function(){
alert("when success");
},
error:function(){
alert('when unsuccess');
}
});
$('#commentForm').ajaxSubmit();
// return false to prevent normal browser submit and page navigation
return false;
});
</script>
</body>
</html>
$.validator.addMethod("requiredFieldCheck", function (value, element) {
alert("working method requiredFieldCheck "+value);
var result;
if(value.length > 3){
result = true ;
}
else{
result = false ;
}
return result;
}, '****This content must be greater than 3 characters****');
And also in the browser console it is caught by an error Uncaught TypeError: undefined is not a function
Can anyone give me some suggestions to do form validation before sending data and essesntially using jquery validation plugin?
Thanks in Advance
you need to register adapter, for example:
jQuery.validator.unobtrusive.adapters.addSingleVal("requiredFieldCheck", "other");

jQuery: Validating fields before submitting (multistep form)

I have a form which consists of 2 steps. What I'd like to do is validate each step before continuing to the next; the user should not be able to get to step 2 of step 1's fields are invalid.
js fiddle: http://jsfiddle.net/Egyhc/
Below you can find the simplified version of the form:
<form>
<div id="step1" style="display: block;">
<label for="first_name">First Name</label>
<input type="text" value="" name="first_name" id="FirstName"/>
<label for="last_name">Last Name</label>
<input type="text" value="" name="last_name" id="LastName"/>
</div>
<div id="step2" style="display: none;">
<label for="first_name">Address</label>
<input type="text" value="" name="address" id="Address"/>
</div>
Continue to step 2
<input type="submit" id="submit_btn" value="Verstuur" style="display: none;" />
</form>
​
$(function() {
$('#step1_btn').click(function() {
$('#step1').hide();
$('#step2, #submit_btn').show();
});
});​
How do you guys suggest I achieve this?
There's a very neat setting of jQuery validate that lets you ignore validation on hidden fields. So you can handle the show/hide logic of your steps and for validation you could just do this:
As this suggests: ignore hidden
$("form").validate({
ignore: ":hidden"
});
If you need to check for validation on something besides the default form submit, you can use the valid method like this: $("form").valid().
I noticed you don't have any validation classes on your form, so I'm assuming you're handling that somewhere else. Just in case you're not, you can tell jQuery validate your rules through css classes like this: <input type="text" class="required digits"/>
See more here: http://bassistance.de/2008/01/30/jquery-validation-plugin-overview/

Categories

Resources