[英]multiple form validation error message in single alert message javascript
I am trying to achieve functionality of showing multiple validation error messages in single alert message. 我正在尝试实现在单个警报消息中显示多个验证错误消息的功能。
i have three text fields, checking whether user entered a value or not in that text field. 我有三个文本字段,检查用户是否在该文本字段中输入了值。 if user does not entered any value and tries to submit form, I have to show to the user that three field are mandatory.
如果用户未输入任何值并尝试提交表单,则必须向用户显示三个字段是必填字段。
piece of code as below : 一段代码如下:
function validateInput(ele, note, Name)
{
var val = ele.value;
if (val == '')
{
note = note +Name+"element can not be Empty; \n";
return false;
}
return true;
}
function validateForm() {
var note = "";
var ele1 = validateInput(document.getElementById('input1'), note, 'From');
var ele2 = validateInput(document.getElementById('input2'), note, 'To');
var ele3 = validateInput(document.getElementById('input3'), note, 'CC');
alert(note);
return (ele1 && ele2 && ele3);
}
You could use an object to pass values by reference, but for this it isn't necessary. 您可以使用一个对象通过引用传递值,但为此没有必要。 Try this:
尝试这个:
function validateInput(ele, Name)
{
var val = ele.value;
return val == '' ? note +Name+"element can not be Empty; \n" : "";
}
function validateForm() {
var note = "";
note += validateInput(document.getElementById('input1'), 'From');
note += validateInput(document.getElementById('input2'), 'To');
note += validateInput(document.getElementById('input3'), 'CC');
var isValid = note == "";
if( !isValid )
alert(note);
return isValid;
}
Strings are not references to String object instance. 字符串不是对String对象实例的引用。
You should declare the note
var in parent context: 您应该在父上下文中声明
note
var:
var note = '';
function validateInput(ele, Name)
{
var val = ele.value;
if (val == '')
{
note = note +Name+"element can not be Empty; \n";
return false;
}
return true;
}
function validateForm() {
note = "";
var ele1 = validateInput(document.getElementById('input1'), 'From');
var ele2 = validateInput(document.getElementById('input2'), 'To');
var ele3 = validateInput(document.getElementById('input3'), 'CC');
alert(note);
return (ele1 && ele2 && ele3);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.