0

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
  }
}
6
  • What is myForm? A string? A DOM element? Commented Aug 10, 2015 at 10:53
  • You might like to use HTML5 <input type="email" pattern ="RegEXP">.. u need to supply regexp only if u want something extra from default.. Commented Aug 10, 2015 at 10:54
  • similar question asked here stackoverflow.com/questions/22174977/… Use Jquery validator Commented Aug 10, 2015 at 10:54
  • You appear to have a solution in your question. What problem do you have? Commented Aug 10, 2015 at 10:55
  • You shouldn't be doing javascript-only validation, unless you have backend validation too, as someone can simply bypass it by disabling javascript Commented Aug 10, 2015 at 11:00

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.