我正在进行客户端表单验证以检查密码是否匹配.但验证功能总是返回undefined.
function validatePassword(errorMessage)
{
var password = document.getElementById("password");
var confirm_password = document.getElementById("password_confirm");
if(password.value)
{
// Check if confirm_password matches
if(password.value != confirm_password.value)
{
return false;
}
}
else
{
// If password is empty but confirm password is not
if(confirm_password.value)
{
return false;
}
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
请注意,validatePassword从Form对象的成员函数调用.
function Form(validation_fn)
{
// Do other stuff
this.submit_btn = document.getElementById("submit");
this.validation_fn = validation_fn;
}
Form.prototype.submit = funciton()
{
var result;
if(this.validation_fn)
{
result = this.validation_fn();
}
//result is always undefined
if(result)
{
//do other stuff
}
}
Run Code Online (Sandbox Code Playgroud)
pim*_*vdb 13
你可以简化这个:
这将导致this,它将始终返回一个布尔值.你的函数也应该总是返回一个布尔值,但如果你简化代码,你可以看到它做得更好:
function validatePassword()
{
var password = document.getElementById("password");
var confirm_password = document.getElementById("password_confirm");
return password.value !== "" && password.value === confirm_password.value;
// not empty and equal
}
Run Code Online (Sandbox Code Playgroud)
您可以将返回值包装在布尔函数中
Boolean([return value])
Run Code Online (Sandbox Code Playgroud)
这将确保所有虚假值都是错误的,并且真实的陈述是真实的.
| 归档时间: |
|
| 查看次数: |
126708 次 |
| 最近记录: |