简体   繁体   中英

RegEx and JavaScript error alerts

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM