1

I noticed that some validation tools use the "class" attribute to pass options to validation scripts.

Example:

<input class="input-field validate[required, email]" name="" type="text" />

the "required" and "email" would be picked up by the script as setting options.

I was wondering is there an easy way to achieve this or maybe this is already available in jQuery? I want to use this as a means of passing certain settings to my script.

Any help would be appreciated, Thanks

Edit:

Thanks @loseb your example works great. Another thing I am trying to achieve by doing some small modification to your example:

function classAttributes( classString, className ) {
    var data;
    var regex = new RegExp(className+"\[(.*?)\]");
    var matches = classString.match(regex);

    if ( matches ) {
        //matches[1] refers to options inside [] "required, email, ..."
            var spec = matches[1].split(/,\s*/);

            if ( spec.length > 0 ) {
                data = spec;
            }
    }

    return data;
}

any idea why "new RegExp(className+"[(.*?)]");" doesnt work. var matches is blank.

Edit: second part of the question moved to: javascript regex pattern with a variable string not working

2 Answers 2

2

If I understand you correctly this is the solution:

var className = $('.input-field').att('class');
var regex = /validate\[(.*?)\]/;
var matches = className.match(regex);

if (matches) {
    //matches[1] refers to "required, email" string
    var spec = matches[1].split(/,\s*/);

    if (spec.length == 2) {
        var attribute = spec[0]; //required or optional or anything else
        var validator = spec[1]; //actual validation type
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I would just use data to do this instead:

var mydata={required: true,email:false}; $('.input-field').data('validate',mydata);

see an example here:http://jsfiddle.net/MarkSchultheiss/FzaA8/

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.