I am using this for form validation. I call this function when there is an error and i send it a string as a parameter.
var errList = new Array();
function aerrorList(error){
errList.push(error);
for (var i=0; i < errList.length; i++){
alert(errList[i]);
}
}
here is one of the validation checks:
function lNameValidate() {
var lName = document.getElementById("lastname");
if (lName.value.length < 20 && /^[a-zA-Z0-9- ]*$/.test(lName.value)){
stNumValidate();
} else {
lName.style.border = "red";
errorList("Invalid lName Format");
stNumValidate();
}
}
The current array (using alert) displays the error in a number of popup boxes with only 1 error string each. i want it to display 1 alert which would show all the errors in a list similar to outputting it in a bullet point way.
您可以将所有错误附加到一个var
,然后显示它:
function aerrorList(error){ errList.push(error); var errors = ""; for (var i=0; i < errList.length; i++){ errors += errList[i] + "\\n"; } alert(errors); }
You could use join
method on an array, Here's an example:
errors=['error1','error2','error3']
Here, a is an array of list of your errors, now you can glue them together using whatever you want like this:
error_string=error.join("\\n*")
Finally you can make an alert:
alert(error_string)
Try this:
var Errors = { messages: [], push: function(message) { this.messages.push(message); }, alert: function() { alert(this.messages.join("\\n")); }, showInElement: function(element) { element.innerHTML = this.messages.join('<br/>'); }, clear: function() { this.messages = []; } } var age = 1; if(age < 18) { Errors.push("Come back when You 18+"); } var name = "Jack"; if(name != "John") { Errors.push("You're not John!"); } Errors.alert(); var element = document.getElementById('content'); Errors.showInElement(element); Errors.clear();
<div id="content"></div>
So I ended up using this:
var errList = new Array();
function errorList(error){
errList.push(error);
}
function showErrors() {
alert(errList.join("\n"));
}
where i just call showErrors on the very last validation check if the errList length is > 1 as such:
function emailRestrict() {
var eVal = document.getElementById("email").value;
var atPos = eVal.indexOf("@");
var dotPos = eVal.lastIndexOf(".");
if (atPos < 1 || dotPos < atPos || dotPos >= eVal.length) {
errorList("not valid email");
if (errList.length > 1){
showErrors();
}
return false;
}
else {
if (errList.length > 1){
showErrors();
}
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.