Reputation: 195
After help from here where the solution works in the fiddle in the simplest form. But while implementing it, it does not work. So I have added the actual code with the solution given previously.
What I am trying to do is check for illegal characters in any of the input box and text area? Fiddle with actual code is here. Actual Code
$('.formsubfree').click(function () {
var str = $(this).prevAll("input, textarea").first().val();
if (/[%&<>\[\]{}]/.test(str) === true) {
alert('These characters & < > [ ] { } % are not allowed. Please remove them and try again.');
}
});
Earlier Solution with the stripped out html is here in fiddle
Thanks
Upvotes: 1
Views: 4533
Reputation: 253308
My suggestion, with your current HTML, would be:
$('.formsubfree').click(function () {
var invalid = ['%', '&', '<', '>', '[', ']', '{', '}'],
validate = $(this).prevAll(':input').first();
if (/[%&<>\[\]{}]/.test(validate.val())) {
console.log("Yeah, these characters ('" + invalid.join(', ') + "') aren't allowed. So stop it.");
}
});
Or possibly:
$('.formsubfree').click(function (e) {
e.preventDefault(); // stop the submission of the form
var validate = $(this).prevAll(':input').first(),
found;
if (/[%&<>\[\]{}]/.test(validate.val())) {
found = validate.val().replace(/[^%&<>\[\]{}]/g,'').split('').join("', '");
console.log(found);
console.log("Yeah, these characters '" + found + "' aren't allowed. So stop it.");
}
else {
// if no errors were found, submit the form:
$('.formsubfree').closest('form').submit();
}
});
References:
Upvotes: 1
Reputation: 1800
You can use validator method with custom rules like this:
$.validator.addMethod("regex", function(value, element) {
return this.optional(element) || value === "NA"
|| value.match(/^[0-9,\[email protected] ]+$/);
}, "Please enter a valid character");
It will discard all the characters except 0-9, A-Z, a-z, @,+,-and .
Upvotes: 0