Reputation: 215
I am new to JavaScript and particularly, working with Regular Expressions. I was wondering, if I define a regEx that checks for a number of different errors, how can I generate individual error alerts for each error, rather than one message that covers all the errors found? for example, this expression prompts an alert box is the input field is numbers, if there are spaces, or the defined invalid characters are found. How can I generate alerts that refer to each condition individually, ie, if the problem is only that a space is found, that's all the message says:
var pattern = /[\d+\s#!%&*:<>?/{|}]/
if(document.myform.usernameInput.value.match(pattern)){
alert("do not use numbers, spaces or invalid caharacters: #%&*:<>?/{|}")
Upvotes: 0
Views: 893
Reputation: 2368
The simplest way is to use several regExps:
function check(str) {
var digits = /\d/;
var spaces = /\ /;
var chars = /[\#\!\%\&\*\:\<\>\?\/\{\|\}]/;
if(str.match(digits)){
alert("do not use numbers");
return false;
};
if(str.match(spaces)){
alert("do not use numbers");
return false;
};
if(str.match(chars)){
alert("do not use invalid caharacters: #%&*:<>?/{|}");
return false;
};
return true;
}
Upvotes: 1