jsldnppl
jsldnppl

Reputation: 913

JS: Form validation on input type

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
  }
}

Upvotes: 0

Views: 137

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075587

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, e.g.:

$(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...

Upvotes: 4

arpan sharma
arpan sharma

Reputation: 64

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.

Upvotes: -1

Related Questions