validate name with jquery with some custom functions - javascript

I am working on simple form validation with jQuery
In fact I used jQuery plugin to validate email address field, now I wanna put an individual validation for name field I tried it too, but it's not working and I am unable to figure out the problem behind.
<html>
<head>
<meta charset="utf-8">
<title>Makes "field" required and an email address.</title>
<link rel="stylesheet" href="main.css" type="text/css" />
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script language="javascript" type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.10.0/jquery.validate.min.js"></script>
<script>
$(function() {
$( "#myform" ).validate({
rules: {
name: {
required: true,
minlength: 4,
maxlength: 20,
customvalidation: true
}
},
messages: {
name: {
required: "Dude, enter a name",
minlength: $.format("Keep typing, at least {0} characters required!"),
maxlength: $.format("Whoa! Maximum {0} characters allowed!")
}
}
});
$.validator.addMethod("customvalidation",
function(value, element) {
return /^[A-Za-z\d=#$%#_ -]+$/.test(value);
},
"Sorry, no special characters allowed"
);
});
</script>
</head>
<body>
<div id="navbar">
<ul id="nav">
<li><a id="clickBack" href="backPage.htm">clickBack</a></li>
<li><a id="clickForward" href="forwardPage.htm">goForward</a></li>
</ul>
</div><br><br>
<label for="field"> Name: </label>
<input class="left" id="name" name="name" minlength="4" class="required name"/>
<br/>
<form id="myform" method="post" action="">
<label for="field">Email: </label>
<input class="left" id="field" name="field" />
<br/>
<input type="submit" value="Submit">
</form>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://jquery.bassistance.de/validate/jquery.validate.js"></script>
<script src="http://jquery.bassistance.de/validate/additional-methods.js"></script>
<script>
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myform" ).validate({
rules: {
field: {
required: true,
email: true
}
}
});
</script>
</body>
</html>
need some guidance... Thanks.

Try using this best JQuery validation plugin
username: {
required: true,
minlength: 2
},
messages: {
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
If you want custom validation you can try this:
$.validator.addMethod("customvalidation", function(value, element) {
return this.optional(element) || /^[a-z0-9\-]+$/i.test(value);
}, "Username must contain only letters, numbers, or dashes.");

Hi a few points which might help this work :
Try use an id that is not "reserved" or ambiguos (since name is already an attribute of the element it could be misleading. When I got your script working on my side, it would work with id="firstName" for eg. but not id="name")
Make sure the element you're validating is in the form you're running the validation on (in your code sample, the name element is sitting outside myform
Combine the two $("#myform").validate(...) methods in two different script blocks, you don't need a seperate one for email and name, you can list them together!
Hope that helps, good luck!

Related

In Jquery-Validate, how to refer to the name of an attribute in label?

I'd like to use the label text as the validation message. In order to do this, I tried to use $(label[for="nameAttrName"]), snippet here:
$("#myForm").validate({
rules: {
NameQuery: "required"
},
messages: {
NameQuery: "Please fill in " + $(`label[for="NameQuery"]`).text()
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/additional-methods.min.js"></script>
<form id="myForm">
<label for="NameQuery">Name Query </label>
<input name="NameQuery"/>
<input type="submit" value="Submit"/>
</form>
Question is, how can I refer to the attribute name in the for="" bit so I don't have to write for="NameQuery" explicitly? Like this
Question is, how can I refer to the attribute name in the for="" bit so I don't have to write for="NameQuery" explicitly?
Not sure why you would ever need to write this generically since you must list each and every field explicitly within the rules and messages objects anyway.
However, you could generically target the previous label element relative to the field being validated...
"Please fill in " + $(element).prev('label').text();
And it must be returned from within a function() in order to obtain the element argument from the plugin...
....
required: function(params, element) {
return "Please fill in " + $(element).prev('label').text();
}
....
DEMO:
$("#myForm").validate({
rules: {
NameQuery: {
required: true
}
},
messages: {
NameQuery: {
required: function(params, element) {
return "Please fill in " + $(element).prev('label').text();
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/additional-methods.min.js"></script>
<form id="myForm">
<label for="NameQuery">Name Query </label>
<input type="text" name="NameQuery" />
<input type="submit" value="Submit"/>
</form>

Javascript: Allow Only Values less than input initial value

on my form, I have many text input fields with pre-filled decimal values, the user can edit the values before submitting the form.
I was wondering if there is anyway using javascript/jquery, to make each input allow only values less than its initial value.
I find it quite challenging, so I thought about posting it here.
Thank you guys
Use jQuery Validation plugin's max method.
Example:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Makes "field" required and 23 or smaller.</title>
<link rel="stylesheet" href="http://jqueryvalidation.org/files/demo/site-demos.css">
</head>
<body>
<form id="myform">
<label for="field">Required, maximum value 23: </label>
<input type="text" class="left" id="field" name="field">
<br/>
<input type="submit" value="Validate!">
</form>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>
<script>
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myform" ).validate({
rules: {
field: {
required: true,
max: $('your_input_selector').val()
}
}
});
</script>
</body>
</html>
This may help you:
var initialValue = $("#myTextbox1").val()
$("#myTextbox1").on("input", function() {
if($("#myTextbox1").val() > initialValue) {
$("#myTextbox1").val(initialValue);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="myTextbox1" type="text" value="5"/>
This solution converts the input into a number, prevents default form action, checks if the input value is a number and if not it alerts the user and resets the default input value, checks to see if the new value is less the the original and if it is not it resets the input to the original value.
HTML
<form id="myForm" action="">
<input type="text" id="myValue" value="5" />
<input type="button" id="myButton" value="validate" />
</form>
JavaScript
var origVal = $('#myValue').val();
$('#myButton').on('click', function(e) {
var getVal = Number($('#myValue').val());
e.preventDefault();
if (isNaN(getVal) === true) {
alert('The input value has to be a number.');
$('#myValue').val(origVal);
}
if (getVal > origVal) {
alert('The input value has to be less than the original value of ' + origVal);
$('#myValue').val(origVal);
}
});

My jQuery form validation isn't working

I'm trying to make this piece of code work. But there is something wrong with it. I don't know what. Anyone care to help here.
Thanks
The problem is that when the form is submitted and it doesn't show any validation messages.
<?php
session_start();
include 'connection.php';
if(isset($_POST['submit'])){
$name=$_POST['name'];
$f_name=$_POST['f_name'];
$cell=$_POST['cell_no'];
$_SESSION['name']=$name;
$_SESSION['f_name']=$f_name;
$_SESSION['cell']=$cell;
}
?>
<html>
<head>
<script src="jquery-1.3.1.min.js">
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script type="text/javascript"></script>
<script>
$(document).ready(function() {
$("#myForm").validate({
rules: {
name: "required",
f_name: "required",
cell_no: {
required: true,
minlenght: 11
}
},
messages: {
name: "Please state your name.",
f_name: "Father name is required.",
cell_no: {
required: "Please provide a contact number.",
minlength: "Minimum length is 11 digits"
}
},
submitHandler: function(form) {
form.submit();
}
});
});
</script>
</head>
<body>
<center>
<?php
echo #$_GET['sheikh'];
?>
</center>
<form method="POST" action="" id="myForm" novalidate="novalidate">
<center><h1>First Form</h1></center>
<h2>Basic Information</h2>
Name:<input type="text" name="name">
Father name:<input type="text" name="f_name">
Cell_no:<input type="text" name="cell_no">
<input type="submit" name="submit" value="next">
</form>
</body>
</html>
Please try checking the console log when you have this kind of issues.
You will come to know what is the problem.
when the page loads it shows,
"Uncaught TypeError: $(...).validate is not a function"
this means the required library not exists with you code.
Download it and insert in your page like
script src="jquery-1.3.1.min.js"
you did or give direct link if you doing this for learning purpose.
Problems in your script:
You have included jQuery twice on the page
You haven't included jQuery.validate.js

jquery validate for my login page is not working

I am very new to jquery & javascript working on login page where Iam using simple jquery validation code. To check whether my username as john and the password pass if it was correct it has to redirect to other page. Else I need to show an error message.
<script type="text/javascript">
$(document).ready(function () {
$("#form1").validate({
debug: false,
rules: {
name: "required",
password: {
required: true,
minlength: 8
}
},
messages: {
name: "Please enter your name.",
password: "Please enter 8 letters minimum.",
}
});
});
</script>
The above code was checking the first rule where if it is empty or not but this itself not working. I am not getting any error label message.
Here is the fiddle Link
Thanks in advance
Regards
M
Your problem is in your HTML. validate binds properties by their name. Your inputs only have ids and no names. Take a look at my sample (jsfiddle). It performs correctly. You also had mismatching formId on your jquery validate method.
As stated in the comments I also added the external resource to the fiddle (.validate jquery plugin)
Html
<h1>Form Validation Example</h1>
<form id='form1' name='form1' method='post' action='' > <p>
Name: <input type='text' name='name' id='name' class='required' />
</p>
<p>
Email: <input type='text' name='password' id='password' class='required' />
</p>
<p>
<input type='submit' name='Submit' value='Submit' />
</p>
</form>
Javascript
$(document).ready(function(){
$("#form1").validate({
debug: false,
rules: {
name: "required",
password: {
required: true,
minlength: 8
}
},
messages: {
name: "Please enter your name.",
password: "Please enter 8 letters minimum.",
}
});
});

Clear form after submission with jQuery

What's the easiest way to clear this form after refresh. The way I have tried will clear the form but not submit to the database. Could someone else explain to me the best way to do this.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($){
$("#newsletterform").validate({
debug: false,
rules: {
name: "required",
email: {
required: true,
email: true
}
},
messages: {
name: "Please let us know who you are.",
email: "A valid email will help us get in touch with you.",
},
submitHandler: function(form) {
// do other stuff for a valid form
$.post('newsletter.php', $("#newsletterform").serialize(), function(data) {
$('#results').html(data);
});
}
});
});
</script>
</head>
<div id="content">
<div id="newsletter-signup">
<h1>Sign up for News, Updates, and Offers!</h1>
<form id="newsletterform" action="" method="post">
<fieldset>
<ul>
<li>
<label for="name">Name:</label>
<input type="text" name="name" />
</li>
<li>
<label for="email">Email:</label>
<input type="text" name="email" />
</li>
<div id="results"><div>
<li>
<input type="submit" value="submit" name="signup" onclick="" />
</li>
</ul>
</fieldset>
</form>
</div>
</div>
</html>
You can add this to the callback from $.post
$( '#newsletterform' ).each(function(){
this.reset();
});
You can't just call $( '#newsletterform' ).reset() because .reset() is a form object and not a jquery object, or something to that effect. You can read more about it here about half way down the page.
You can reset your form with:
$("#myform")[0].reset();
Better way to reset your form with jQuery is Simply trigger a reset event on your form.
$("#btn1").click(function () {
$("form").trigger("reset");
});
try this in your post methods callback function
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
for more info read this
Propably this would do it for you.
$('input').val('').removeAttr('checked').removeAttr('selected');
A quick reset of the form fields is possible with this jQuery reset function.
$(selector)[0].reset();
Just add this to your Action file in some div or td, so that it comes with incoming XML object
<script type="text/javascript">
$("#formname").resetForm();
</script>
Where "formname" is the id of form you want to edit

Categories

Resources