I'm trying to do some form validation, however don't want to to select form input by class name. Is there a way I can loop through the validation based on input attribute type. I've had a play with the code, but to little avail. Potentially thinking something along these lines:
EDIT: I don't want to use a plugin
function validator (myForm) {
// If type equals Email
if($(myForm + " input").attr("type") == "email") {
// Validate Email Here
}
// If type equal text
if($(myForm + " input").attr("type") == "text") {
// Validate Text Here
}
}
Yes, you can do something like that.
First, if myForm
is a DOM element, then you'll want $(myForm).find(...)
rather than $(myForm + " ...")
, because the latter will result in an invalid selector. If myForm
is a string containing a valid selector, it's fine.
Your if($(myForm + " input").attr("type") == "email") {
won't work because what that will do is get the type
of the first input
in your form and compare it to the string "email"
. It won't find all the email inputs in your form.
You can select specific types of inputs using an attribute selector, eg:
$(myForm).find("input[type=email]").each(function() {
// Validate email inputs; each input is available as `this`,
// which is a DOM element
});
and
$(myForm).find("input[type=text]").each(function() {
// Validate text inputs; each input is available as `this`,
// which is a DOM element
});
(In this case, we don't need quotes around the attribute values because they're single words.)
You might also look into the HTML5 form validation stuff .
And of course, you probably know this, but any validation you do with client-side JavaScript (or other browser features) is purely for UI/UX purposes . You still have to validate things on the server, as client-side validation can be completely bypassed...
you can find input element by attribute like below.
//If type equals Email
$('input [type = email]')
// If type equals Email
$('input [type = text]')
like above you can access.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.