最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to Validate special characters in a textbox and show entered special characters in the error message? - Stack O

programmeradmin0浏览0评论

There is a textbox and a button that validates the entry inside the textbox.
That if it should not validate the presence of illegal characters in the form.
Suppose I entered the following word "Lorem# %ipsum^"

On clicking the button, two things should happen

  • If there sre any special chars like #$%^&, then the form submission should fail.
  • An error message should pop up like "You have used the illegal characters #, % and ^ in your form"

What is the best method?
P.S: I would like a solution not involving jquery.

There is a textbox and a button that validates the entry inside the textbox.
That if it should not validate the presence of illegal characters in the form.
Suppose I entered the following word "Lorem# %ipsum^"

On clicking the button, two things should happen

  • If there sre any special chars like #$%^&, then the form submission should fail.
  • An error message should pop up like "You have used the illegal characters #, % and ^ in your form"

What is the best method?
P.S: I would like a solution not involving jquery.

Share Improve this question asked Aug 24, 2010 at 6:43 codeandcloudcodeandcloud 55.3k47 gold badges168 silver badges259 bronze badges 1
  • 1 Is that really the requirement? Wouldn't it be more sensible to have a message such as 'only letters, digits, underscore and hyphen are allowed'? – karim79 Commented Aug 24, 2010 at 6:46
Add a ment  | 

2 Answers 2

Reset to default 4

You could do this:

var invalidChars = str.match(/[^\w ]/g), output = '';
if (invalidChars) {
    invalidChars = invalidChars.unique();
    var lastInvalidChar = invalidChars.pop();
    output = 'You have used the illegal character' + (invalidChars.length > 0 ? 's' : '') + ' ' +
        invalidChars.join(', ') + (invalidChars.length > 0 ? ' and ' : '') + lastInvalidChar;
}

Here match and the regular expression /[^\w ]/g is used to get all characters that are neither word characters nor a space. The array of matched invalid characters is then cleaned from duplicates using the custom unique method (see below). Then the last invalid character is removed from the array to append it if necessary with an “and” at the end of the output. The remaining invalid characters (if there are any) are then joined with mas and bined with the last invalid character.

Since JavaScript has no built-in unique method to remove duplicates, you can use this method:

Array.prototype.unique = function() {
    var index = {};
    for (var i=0; i<this.length; ++i) {
        if (!index.hasOwnProperty(this[i])) {
            index[this[i]] = this[i];
        }
    }
    var clean = [];
    for (var prop in index) {
        if (index.hasOwnProperty(prop)) {
            clean.push(index[prop]);
        }
    }
    return clean;
};

Note that this implementation is not type-safe as the values are used as property names and thus turned into strings. So ["3",3].unique() returns ["3"] hence "3".toString() === (3).toString().

var myString = document.getElementById("myInputField").value; // gets the sentence
var invalidChars = myString.replace(/[^#%\^]*/g, ""); //gets the chars | "#%^" in your case
var response = "";

for(var  i = 0; i < invalidChars.length; i+){
  response += (i > 0? (i == invalidChars-1 ? " and ": ", "):"") + invalidChars[i];
}

if (response != "") {
  alert("Your data contains invalid characters " + response);
}

For more info on js regexes check out

http://www.regular-expressions.info/javascript.html

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论