0

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: #%&*:<>?/{|}")

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this is what I did, I just wasn't sure if there was a more elegant way, or whether each needed to be tested with its own regEx. Thank you.

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.