jQuery form processing: require vs. not required
I'm building a form system with jquery and using basic validation (if a form has the required values and is of the required type) as a front line system (I validate at the backend too) for validating as the user submits, this is to prevent useless requests when possible (eg: submitted a completely empty form)
What is the "proper" way to handle this? My default idea is to apply a class to the elements, like so:
<input type="text" name="something" class="required">
or
<input type="text" name="something" class="optional">
and then simply looping through and checking if the classes match, is this an "okay" way to do it or is there a better way? I could apply cu开发者_如何学编程stom attributes but I'd feel bad and I don't know if all browsers support this.
Note: These fields aren't necessarily the same every time, hard coding into the js isn't a possibility (or imo a good idea).
You may want to check out the JQuery validation plugin.
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
We're using a class name syntax as such:
validate[required]
validate[phone]
etc.
That way we can easily apply multiple validation rules via class names but keep a consistent syntax.
We're also going to look into using some of the HTML 5 'type' attributes to see if we can leverage that for some validation as well.
There is already a plugin for jQuery which does exactly what you're proposing to do, you can add validations through the class attribute of the element (and there are other ways to add validation too).
You can see his documentation at: http://docs.jquery.com/Plugins/Validation
Backing to your question, I think it's a "okay" way to do this. And it's quite easy with jQuery.
I'm glad if it helped.
There are many ways to do form validation and there is a lot of code out there that already does it.
You could look into the jQuery Validation plugin which will let you create markup similar to the one you posted and that will do the validation for you. For example, if you have an input form that looks like this :
<form id="inputform">
<p>
<label>Name</label>
<input id="name" class="required" />
</p>
<p>
<label>E-Mail</label>
<input id="email" class="required email" />
</p>
</form>
All you would have to do to validate it would be
$(document).ready(function(){
$("#inputform").validate();
});
If you decide to go without the plugin, you can still find your required elements pretty easily with
$("input.required").each(function() {
// do your validation here
});
精彩评论