I need to validate another ready made bad words filter after validating first rules (blank fields). I have all codes in ready made, someone please help me to add this second validation in my page.
This is my jquery codes where I need to include the 2nd validation.
$(function() {
$("#review").focus(function() {
$("#comments").removeClass('hide')
});
$("#sky-form").validate({
rules: {
digits: {
required: true,
digits: true
},
name: {
required: true
}
},
messages: {
digits: {
required: 'Please enter a valid amount of Money'
},
name: {
required: 'Please enter your username',
}
},
submitHandler: function(g) {
$(g).ajaxSubmit({
beforeSend: function() {
$('#sky-form button[type="submit"]').attr('disabled', true)
},
success: function() {success funtion goes here}
This is the 2nd validation codes that I need to include on top. Mainly I need this function - bwords=badwords(textbox_val); - It will verify bad word's after blank fields is okay.
<script language="javascript" type="text/javascript">
function Message()
{
var textbox_val=document.form.textbox.value;
if(textbox_val=="")
{
alert("Please enter a message");
return false;
}
bwords=badwords(textbox_val);
if(bwords>0)
{
alert("Your message contains inappropriate words. Please clean up your message.");
document.form.textbox.focus();
return false;
}
}
</script>
Those both function is working but I just need to include both validation like 2nd one in the top first script.
Sorry for my bad Enlgish.
You can add a new rule in your code. I called this rule badWords and for me the
bad word is BAD so when you try to type BAD in the name field you will get the
validation error message.
$.validator.addMethod("badWords", function(value, element) {
if (value.trim().length == 0) {
return false;
}
if (value == 'BAD') {
return false;
}
return true;
}, "BAD WORD");
$(function () {
$("#sky-form").validate({
rules: {
digits: {
required: true,
digits: true
},
name: {
required: true,
badWords: true
}
},
messages: {
digits: {
required: 'Please enter a valid amount of Money'
},
name: {
required: 'Please enter your username',
}
}
});
});
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.js"></script>
<form id="sky-form">
<label for="ele1">Digits:</label>
<input type="text" id="ele1" name="digits"/>
<br/>
<label for="ele2">Name:</label>
<input type="text" id="ele2" name="name"/>
<br/>
<input type="submit" id="submit"/>
</form>
Related
Below is my javascript code. As you have noticed, in my $("#register-form").validate the rules are all the same, which is required:true . since it's just that, I wanted to make it required in their input fields instead in the html. I did try it, therefore I deleted the entire code inside the comment /* validation */ and added required in each of their input fields in my html form, but when I submit the form, it just reloads the page, not giving me the messages I was expecting in my function submitForm(). But if I use the entire code, it is submitting the form and gives me the correct alert message. So how will I disregard the rules and messages here? Since I already have required in my html input fields?
$('document').ready(function()
{
/* validation */
$("#register-form").validate({
rules:
{
firstname: {
required: true
},
lastname: {
required: true
},
username: {
required: true,
minlength: 8
},
password: {
required: true,
minlength: 8
},
password2: {
required: true,
equalTo: '#password'
},
email: {
required: true,
email: true
},
answer: {
required: true
},
},
messages:
{
firstname:"Please input your firstname.",
lastname:"Please input your lastname.",
answer:"Please input your answer.",
username:{
required: "Please input your username.",
minlength: "Username must be atleast 8 characters"
},
password:{
required: "Please input your password",
minlength: "Password must be atleast 8 characters"
},
email: "Please enter a valid email address",
password2:{
required: "Please re-type your password",
equalTo: "Password do not match!"
}
},
submitHandler: submitForm
});
/* validation */
/* form submit */
function submitForm()
{
var data = $("#register-form").serialize();
$.ajax({
type : 'POST',
url : 'signup.php',
data : data,
beforeSend: function()
{
$("#error").fadeOut();
},
success : function(data)
{
if(data==2){
$("#error").fadeIn(1000, function(){
alert('Email is already taken.');
document.getElementById ("email").focus();
});
}
else if(data==1){
$("#error").fadeIn(1000, function(){
alert('Username is already taken.');
document.getElementById ("username").focus();
});
}
else if(data==3)
{
alert('Registration successfully submitted.');
window.location='index.php';
}
else{
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> '+data+' !</div>');
$("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> Create Account');
});
}
}
});
return false;
}
/* form submit */
});
Well you are using a plugin to validate your input and it calls the submitHandler function when tests pass. So if you want to get rid of that validation you need to bind your submitForm function to a submit event...
$('document')
.ready(function () {
/* form submit */
function submitForm() {
//do stuff and return false
return false;
}
/* form submit */
$("#register-form").on("submit",submitForm);
});
Can someone help me understand why onkeyup validation is not working? I have been staring at it too long! Thanks.
JSFiddle here.
Code:
$(document).ready(function () {
jQuery('#DSH0000000146FF').validate({
rules: {
dish_name: {
required: true
},
dish_description: {
required: true
}
},
messages: {
dish_name: {
required: "Please enter a name, no longer than 80 characters."
},
dish_description: {
required: "Please enter a description, no longer than 240 characters."
}
},
submitHandler: function (form) {
if(jQuery('#DSH0000000146FF').validate()){
alert("SUBMITTED!");
}
else{
}
}
});
});
Add submit button to form
<textarea id="DSH0000000146d" name="dish_description"
class="textarea-comment dish_description" maxlength="240">More testing
</textarea><br/>
<input type="submit"></input> <!-- Add this line -->
jsfiddle
I want to validate password and confirm password in HTML5. By using function required I have validated for empty value. But not able to validate password and confirm password
HTML:
<form id="registration" name="registration" action="registrationaction.php" method="POST">
<input type="password" class="agent-input registerinput" name="pswd" id="pswd">
<input type="password" class="agent-input registerinput " name="confirmpassword" id="confirmpassword">
</form>
JavaScript:
<script>
$().ready(function()
{
$("#registration").validate({
rules: pswd: {
required: true
},
confirmpassword: {
required: true
},
},
messages
pswd: "Please enter password",
confirmpassword: "Please enter valid confirm password",
},
submitHandler: function() { $('#registration').submit(); }
});
});
There are several methods to confirm the two password match. However, assuming you want to utilize the jQuery Validation Plugin (which your question seems to use), changing your Javascript code to this will do the job:
$().ready(function(){
$("#registration").validate({
rules: {
pswd: {
required: true
},
confirmpassword: {
required: true,
equalTo: "#pswd"
}
},
messages: {
pswd: "Please enter password",
confirmpassword: "Please enter valid confirm password"
},
submitHandler: function() { $('#registration').submit(); }
});
});
I should point out that your Javascript example had several issues (unclosed brackets, etc). They've been corrected in the example above.
And for more amazingness you can create with jQuery Validation Plugin, definitely remember to see their documentation webpage for an easy-to-read list of available options.
P.S.
To everyone insisting that $().ready() must be changed, I'd like to point out that it is perfectly valid syntax according to the jQuery documentation (although not recommended, it is valid).
You should write your code within proper ready() function. I think the code you have provided must be throwing errors. Anyhow two correct ways to do this would be:
$( document ).ready(function() {
//your code comes here
});
$(function() {
//your code comes here
});
Inside these you can write the form validation code. Please be clear on the point that you can only do this with JavaScript.
$(document).ready(function() {
$("#registration").validate({
rules: pswd: {
required: true
},
confirmpassword: {
required: true
},
},
messages
pswd: "Please enter password",
confirmpassword: "Please enter valid confirm password",
},
submitHandler: function() { $('#registration').submit(); }
});
});
OR
$(function() {
$("#registration").validate({
rules: pswd: {
required: true
},
confirmpassword: {
required: true
},
},
messages
pswd: "Please enter password",
confirmpassword: "Please enter valid confirm password",
},
submitHandler: function() { $('#registration').submit(); }
});
});
both function $(document).ready(function() { // code here }); and $(function() { // code here }); are equivalent. Don't forget to code for server side validation!!!
I am trying to validate my form using jQuery Validation plugin.
Here is the code
$(document).ready(function(){
var productsForm=$('#products-form');
productsForm.validate({
//debug:true,
invalidHandler: function(event, validator) {
// 'this' refers to the form
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'You missed 1 field. It has been highlighted'
: 'You missed ' + errors + ' fields. They have been highlighted';
$("div.error span").html(message);
$("div.error").show();
} else {
$("div.error").hide();
}
},
rules:{
productName: {
required: true,
minlength:2,
//here i tried to create a function
onfocusout: function(element){
var myValue=$(element).val();
if(myValue.match(/[<>$]/))
{
alert('Please enter the Name without any tags.');
$(element).valid=false;
}
}
},
productType: {
required: true,
minlength:2,
},
productBrand: {
required: true,
minlength:2,
},
description: {
required: true,
minlength:10,
maxlength:150,
},
updatedBy:{
required:true,
minlength:2,
}
},
messages:{
productName:{
required: "Please enter the productName",
minLength: "The name should be atleast 2 characters long",
},
productType: {
required: "Please enter the productType",
minlength:"The type should be atleast 2 characters long",
},
productBrand: {
required: "Please enter the productBrand",
minlength:"The Brand Name should be atleast 2 characters long",
},
description: {
required: "Please describe your product",
minlength: "The description should be atleast 10 characters long",
maxlength: "You can not enter more than 150 characters",
},
updatedBy:{
required: "PLease Your name",
minlength: "The name should be atleast 2 characters long",
}
},
submitHandler: function(form){
if(productsForm.valid())
{
alert('tada');
return false;
}
else
{
alert('not valid');
return false;
}
}
});
});
Now I am trying to create a function which checks whether the input values contain HTML tags or not. If yes then show the error msg and do not submit the form. But I do not know how to do that. Can anyone help please?
I tried to create a function as onfocusout but do not know how to add error.
Quote Title:
"how to check for HTML tags and then add error in jQuery Validation"
If you're using the jQuery Validate plugin, you only need to specify a rule for a field and the corresponding error message is toggled automatically. There are built-in methods for creating custom rules and built-in methods for over-riding any error text with your custom text. The plugin automatically blocks the form submission during any error including errors triggered from your custom rules.
Quote OP:
"Now I am trying to create a function which checks whether the input
values contain html tags or not. If yes then show the error msg and
do not submit the form."
Your second sentence merely describes what every single validation rule does. Checks the input data and blocks submission on failure of this test. Your first sentence is what you want your rule to do... make sure the input contains no tags.
Quote OP:
"I tried to create a function as onfocusout but do not know how to add error."
Your code attempt indicates that you're making this way way more complicated than it needs to be. You do not need to tinker with any single callback function of the plugin just to create one new rule... at that point you might as well write your own validation plugin from scratch.
To achieve what you want, you simply need to use the addMethod method to write your own custom jQuery Validation rule. In this case, you'll need a regex that will exclude HTML tags... perhaps by only allowing letters and numbers. (Tweak the regex or replace the function with anything you see fit).
Refer to this really basic example:
jQuery.validator.addMethod("noHTML", function(value, element) {
// return true - means the field passed validation
// return false - means the field failed validation and it triggers the error
return this.optional(element) || /^([a-z0-9]+)$/.test(value);
}, "No HTML tags are allowed!");
$('#myform').validate({
rules: {
field1: {
required: true,
noHTML: true
}
}
});
DEMO: http://jsfiddle.net/mM2JF/
However, the additional-methods.js file already includes various rules that would automatically exclude any HTML...
letterswithbasicpunc => "Letters or punctuation only please"
alphanumeric => "Letters, numbers, and underscores only please"
lettersonly => "Letters only please"
$('#myform').validate({
rules: {
field1: {
required: true,
alphanumeric: true // <- will also not allow HTML
}
}
});
DEMO 2: http://jsfiddle.net/mM2JF/1/
Try this Code to Validate the HTML tags
jQuery.validator.addMethod("noHTMLtags", function(value, element){
if(this.optional(element) || /<\/?[^>]+(>|$)/g.test(value)){
return false;
} else {
return true;
}
}, "HTML tags are Not allowed.");
$('#form').validate({
rules: {
message: {
required: true , noHTMLtags: true
}
}});
I Hope this is also a good example.
Here is the exmple of what i hve done
$.validator.addMethod("CHECKDOB", function(value, element) {
return this.optional(element) || check_blank_dob(element);
}, "Please Enter Birth Date");
//See checkdob function is added to validator
Now
In rules
rules:{
<%=txtfirstname.UniqueID %>: {required: true}, <%=txtlastname.UniqueID %>: {required: true},
<%=txtdateofbirth.UniqueID %>: { required: true,
CHECKDOB:"Please Enter Birth Date",//see here i have called that function
date:true
},
now messages
messages: {
<%=txtfirstname.UniqueID %>:{required: "Please Enter First Name"},
<%=txtlastname.UniqueID %>:{required: "Please Enter Last Name"},
<%=txtdateofbirth.UniqueID %>:{
required: "Please Enter Birth Date",
CHECKDOB:"Please Enter Birth Date",
date:"Invalid Date! Please try again"
},
Here is your function
function check_blank_dob()
{
var birth=document.getElementById("<%=txtdateofbirth.ClientID%>").value
if(birth=="__/__/____")
{
return false;
}
return true;
}
See this function i have called at checkdob function when adding method to validator
This is just the example how to add you have to implement your method i hope this will help you regards....:)
I use regular expression for preventing HTML tags in my textarea
$.validator.addMethod(
"no_html",
function(value, element) {
if(/<(.|\n)*?>/g.test( value )){
return false;
}else{
return true;
}
},
"HTML tag is not allow."
);
$('#myform').validate({
rules: {
field1: {
required: true,
no_html: true
}
}
});
I need to put a promotional message either at the bottom of the form or in an alert when a user meets certain criteria. I think an alert might be best. It's to do with certain postcodes so I will need to write a regex (I haven't done this yet). It needs to happen when the user clicks submit and before it goes to the server. I'm not sure how to write this and where it should be placed in my script. This is what I have so far if it helps.
$(document).ready(function(){
$("#orderForm").validate({
onfocusout: function(element) {
this.element(element);
},
rules: {
shipFirstName: {
required: true,
},
shipFamilyName: {
required: true,
},
shipPhoneNumber: {
required: true,
},
shipStreetName: {
required: true,
},
shipCity: {
required: true,
},
billEmailAddress: {
required: true,
},
billPhoneNumber: {
required: true,
},
billCardNumber: {
required: true,
},
billCardType: {
required: true,
},
shipPostalCode: {
postalCode: true,
},
fidelityCardNumber: {
creditCardNumber: true,
},
}, //end of rules
}); // end of validate
}); // end of function
$.validator.addMethod('postalCode',
function (value, element)
{
return this.optional(element) || /^[A-Z]{2}\d{1,2}\s\d{1,2}[A-Z]{2}$/.test(value);
}, 'Please enter a valid Postal Code');
$.validator.addMethod('creditCardNumber',
function(value, element)
{
return this.optional(element) || /^[A-Z]{1}([A-Z]|\d){4}\s?([A-Z]|\d){5}\s?([A-Z]|\d){3}\d{1}(\!|\&|\#|\?){1}$/.test(value);
}, 'Please enter a valid card number');
You should be able to do something like this (this will replace the default submit behavior):
$("#orderForm").validate({
submitHandler: function(form) {
// code to display personal message
// code to handle form submission
},
onfocusout: function(element) {
...
Write a click function for submit button and call ajax function in that
$("#submit").click(function(){
alert("This is a promotional message on submit");
//here write ur ajax code.
});
ajax in Jquery.
You need to provide a submitHandler as an option to the validate method.
submitHandler: function(form) {
if ($("form #hasAsked").val() != 'true' && /[MK]{2}[1-15|17|19|77]{2}/.test($("#shipPostalCode").val()) {
openModalDialog();
return false;
}
return true;
},
...
An a function
function openModalDialog() {
$("<div>Wanna buy?? <button value="yes" id="y/><button value="no" id="n/></div>")
.after("body p:first-child")
.show('slide')
.find("#y, #n").click(function() { $("form #hasAsked").val("true") /* default: false */; })
.end()
.find("#y")
.click(function() { $("form #hiddenbuy").val("true"); })
.end()
.find("#n")
.click(function() { $("form #hiddenbuy").val("false"); })
}