I am using the UF Validator on a project and I’d like to add some custom validation checks.
I want to add a username check that gives an error if the input contains anything other than a-z 0-9. No spaces or anything. Similarly I want to add a name check that only allows a-z, but does allow spaces.
I am basing my checks on the built in email validation. Here is the filter:
var mail_filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
And here is the code for the email check:
// E-MAIL VALIDATION
if (obj.hasClass('req-email')) {
tmpresult = mail_filter.test(valAttr);
if (!tmpresult) errorTxt = (valAttr == '') ? opts.errorMsg.reqMailEmpty : opts.errorMsg.reqMailNotValid;
result = result && tmpresult;
}
And here are my filters:
var username_filter = /^[a-zA-Z0-9]/;
var name_filter = /^[a-zA-Z ]/;
And here is my code:
// USERNAME VALIDATION
if (obj.hasClass('req-username')) {
tmpresult = username_filter.test(valAttr);
if (!tmpresult) errorTxt = (valAttr == '') ? opts.errorMsg.reqUsernameEmpty : opts.errorMsg.reqUsernameNotValid;
result = result && tmpresult;
}
// NAME VALIDATION
if (obj.hasClass('req-name')) {
tmpresult = name_filter.test(valAttr);
if (!tmpresult) errorTxt = (valAttr == '') ? opts.errorMsg.reqNameEmpty : opts.errorMsg.reqNameNotValid;
result = result && tmpresult;
}
I have referenced them here as well:
// gather inputs & check is valid
$(merged_options.scope+' .req-email, '+merged_options.scope+' .req-string, '+merged_options.scope+' .req-same, '+merged_options.scope+' .req-both, '+merged_options.scope+' .req-numeric, '+merged_options.scope+' .req-date, '+merged_options.scope+' .req-min, '+merged_options.scope+' .req-username, '+merged_options.scope+' .req-name').each(function() {
thisValid = $.formValidator.validate($(this),merged_options);
boolValid = boolValid && thisValid.error;
if (!thisValid.error) errorMsg = thisValid.message;
});
The corresponding error messages exist as well but I don’t think they need showing.
I thought this would work fine but when I try, it behaves quite strangely. Showing the wrong error messages and not validating it how I want it to. I’ve checked their website and searched on here but can’t find anything relating to it.
Your regex only test for the presence of a single character at the start of the string.
You need to add a
+to indicate that you want to match one or more characters, e.g.[a-z\d]+, or you can specify a range.For example, the regex below specify that the strings must be between 1 and 20 characters long.
The end character
$is needed, or you are only specifying what must be at the start of the string.The
iflag means a case-insensitive match, assuming that is what you want;\dis equivalent to[0-9].