jQuery Validation: Adding Errors to the Error Containter… With Love!
Hello again, my wonderful audience, I have something great and fun planned for this post. If you read this post you might have been left wondering how to add custom messages to the error holder. It's ok if you did, there's nothing wrong with being confused all the time. It's what makes you so adorable.
Say you have a form like this, and if you don't I cry endlessly for your loss. My heart goes out to you.
<form id="ILoveEverythingForm"> <div id="NotSoNiceThingsDiv" style="display:none;"></div> ... </form>
As you can see, there is an error div to hold mean things that we have to print out because the system just doesn't like the user. As we both know, the user can't help but be dumb. It's just in his cute little nature. And that nature is just so darned cute.
Now let's assume that you have something that sent back a bunch of mean messages when you tried to validate server side after all the cute client side validation was done. You might have a method to take in those jerk face messages. How do you display them in the bad place?
function updateErrorDivContentWithLove(messages) { if(messages.length > 0) { var validator = jQuery('#ILoveEverythingForm').validate(); for(var loopCounter = 0; loopCounter < messages.length; loopCounter ++) { validator.showErrors ( { 'SomeWonderfulElementName' : messages[loopCounter].Message } ); } } }
Awwww kitties!
Only thing that may seem odd (And if it doesn't, don't worry you are still very special and loved in this world):
'SomeElementName' : messages[loopCounter].Message
Not sure what element really needs to be here, basically anything in the form with a name tag. So if you're good like I know you are, you have at least one element in that little old form with a name property set. I would say that this is pretty useless in situations where all the errors are shown in one div, as opposed to right next to the element, but that would be mean and I don't do that.
Now I know you wanted something special from this post so I just wanted you to know that even though most of the world considers you hideous, I say you should be proud of being hideous because it makes you who you are. A unique miracle that only really has issues with dogs and small children. Embrace yourself in whatever way you take that!
Custom Data Annotations With MVC: How to Check Multiple Properties at One Time
Ok so maybe you read this post and you're thinking to yourself, "I wonder if Diet Dr. Pepper really does taste like regular Dr. Pepper" which of course is silly because the ads clearly say it does. Now you should be asking yourself, "How do I check if two properties have the same value on a class with annotation when the property level ones only can check the one property's value?" Kind of wordy way of asking that, but I get what you're asking. Better yet, like usual, I have an answer.
Now what I can swear is that I was no where near the Baxter Building between 1-3 am on Saturday the 15th. I was in fact I was sleeping and have 20 witnesses that can testify. What I can't swear is this is the best way to go about it but it seems to work AND make sense. It's not common for me to come up with solutions that do both.
[AttributeUsage(AttributeTargets.Class)] public class PropertiesMatchAttribute : ValidationAttribute { public String FirstPropertyName { get; set; } public String SecondPropertyName { get; set; } //Constructor to take in the property names that are supposed to be checked public PropertiesMatchAttribute(String firstPropertyName, String secondPropertyName ) { FirstPropertyName = firstPropertyName; SecondPropertyName = secondPropertyName ; } public override Boolean IsValid(Object value) { Type objectType = value.GetType(); //Get the property info for the object passed in. This is the class the attribute is // attached to //I would suggest caching this part... at least the PropertyInfo[] PropertyInfo[] neededProperties = objectType.GetProperties() .Where(propertyInfo => propertyInfo.Name == FirstPropertyName || propertyInfo.Name == SecondPropertyName) .ToArray(); if(neededProperties.Count() != 2) { throw new ApplicationException("PropertiesMatchAttribute error on " + objectType.Name); } Boolean isValid = true; //Convert both values to string and compare... Probably could be done better than this // but let's not get bogged down with how dumb I am. We should be concerned about // dumb you are, jerkface. if(!Convert.ToString(neededProperties[0].GetValue(value, null)).Equals(Convert.ToString(neededProperties[1].GetValue(value, null)))) { isValid = false; } return isValid; } } }
And then the use:
[PropertiesMatchAttribute("Password", "ConfirmPassword", ErrorMessage = "Match the passwords, dumb--s.")] public class UserCreateModel { public String ConfirmPassword{ get; set; } public String Password { get; set; } }
Wasn't so hard was it? Normally this would be the part where I degrade you for being bumb because you didn't figure this out but I'm above that now. I guess it must be the holiday season or that I've been told by the board that I should be more gentle with my readers. Guess some were crying after reading some of my posts. Yeah whatever. Bunch of [Removed by Andre].
jQuery Validation – How to Use to Get Rid Of Even The Toughest Stains
So you want to use jQuery validation, huh?
What is it? Something that was added to the holy jquery site and is an easy way to validate input from users. Now this should in no way take over for server side validation, but it helps to at least catch a few things without having to send anything to the server. So how do ya do it?
Well to start, you need some files:
jquery-1.3.2.js and jquery.validate.js.
Now oddly enough the validation file isn't hosted on the holy jquery site but how to use it is.
Ok now you have the files, what's next? Well you need form, and I can do that for you.
So basically it's a simple form with one input that is required.
jQuery(document).ready
(
function()
{
jQuery("#PrimaryForm").validate
(
{
errorLabelContainer: "#ErrorDiv",
wrapper: "div",
rules:
{
FirstName :
{
required : true
}
},
messages:
{
FirstName:
{
required : 'First Name is required.'
}
},
onfocusout : false,
onkeyup: false,
submitHandler: function(label)
{
postSubmit();
}
}
);
}
jQuery("#PrimaryForm").validate
Real simple, just setting the validator to the primary form on the page.
errorLabelContainer: "#ErrorDiv",
This sets the errors to show up in the ErrorDiv. Now this is optional, as you can have it show the errors next to the FirstName text box but personally I think that looks horrible. Setting up the ErrorDiv puts all the errors in one central location and allows for styling the actual div.
rules:
{
FirstName :
{
required : true
}
},
This matches an element with the id of FirstName to the required rule, meaning that FirstName is required. Rocket science.
messages:
{
FirstName:
{
required : 'First Name is required.'
}
},
If you can't figure this out, I hear circus is hiring for the "World's Dumbest Person". You'll fit in with Jub Jub the Dog Boy.
onfocusout : false, onkeyup: false,
Basically this prevents the validation when leaving the textbox or on every key press. This is just another preference.
submitHandler: function(label)
{
postSubmit();
}
If the submit is successful, call this method.
But... BUT WHAT IF IT'S AN EMAIL?!??! WHAT WILL I DO???!?!?
Well for one, stop being such a child. And two, look here.
Some what different, as you can see it's now email and there is one extra requirement in the rules:
rules:
{
EmailAddress :
{
email : true,
required : true
}
},
messages:
{
EmailAddress:
{
required : 'Yo, email fool.',
email : 'So not an email address.'
},
},
See? It has nice built in rule for email. Simple.
BUT WHAT IF I NEED A REGULAR EXPRESSION?!??! WHAT WILL I DO???!?!?
I swear if you don't stop that, I'm turning this post around and going home.
jQuery.validator.addMethod
(
"isZipCode",
function(value, element)
{
return value.match(new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/));
}
);
Just have to create a method and "add it" to the validator itself. And then there's the use:
rules:
{
ZipCode :
{
required : true,
isZipCode : true
}
},
messages:
{
ZipCode:
{
required : 'For the love of me, enter a zip code!.',
isZipCode : 'Serioulsy? Do you know what a zip code is?'
},
},
Woo hoo right?
Don't do it... Don't you yell.
But what if one input depends on another?
Much better. Well that's not as hard as it may seem and here's the example.
rules:
{
InputB :
{
required :
{
depends : function(element) { return jQuery('#InputA').val() != "" }
}
}
},
As you can see, you can change how the required method works by adding in a depends handler. Works out pretty well.
Yes I will show you how to make sure two inputs match. I swear you ask for a lot.
rules:
{
Password :
{
equalTo : "#ConfirmPassword"
},
},
Couldn't be easier unless I wrote it out for you. Wait, I did.
So here you've either learned a bit about jQuery validation or have just spent the last few minutes drooling uncontrollably. Either way, I'm done with this post and you're left to do whatever it is you do, you sick f---.
Side note: I haven't actually been to Htmlgoodies since eh college? but wow did that place sell out. How fitting that an introduction to html page now looks like it was designed by someone just starting out... in the 90s.



