【问题标题】:javascript validating in the wrong orderjavascript以错误的顺序验证
【发布时间】:2015-12-22 01:42:27
【问题描述】:
function validateForm() {
    var name = document.forms["myForm"]["name"].value;
    if (name == undefined || name == null || name == "") {
        alert("Name must be filled out");
        return false;
    }

    var letters = /^[A-Za-z]+$/;
    if (name.match(letters)) {
        return true;
    } else {
        alert('Name must have alphabet characters only');
        document.forms["myForm"]["name"].focus();
        return false;
    }
}

function validateForm() {
    var unit = document.forms["myForm"]["unit"].value;
    if (unit == undefined || unit == null || unit == "") {
        alert("Unit must be filled out");
        return false;
    }

    var alpha = /^[0-9a-zA-Z]+$/;
    if (unit.match(alpha)) {
        return true;
    } else {
        alert('User address must have alphanumeric characters only');
        document.forms["myForm"]["unit"].focus();
        return false;
    }
}

验证有效,但它从单位字段而不是名称开始,当我用正确的字符填写单位字段并提交时,它不会返回验证名称字段,请认真建议?

【问题讨论】:

  • 你有两个同名的函数,为什么?
  • 更正,他有ONE功能,只有第二个:p

标签: javascript html validation


【解决方案1】:

你不能有两个同名的函数,因为第二个函数会覆盖第一个函数。像这样合并函数:

function validateForm() {
    var formIsValid = true;
  
    var name = document.forms["myForm"]["name"].value;
    if (name == undefined || name == null || name == "") {
        alert("Name must be filled out");
        formIsValid = false;
    } else  if (!name.match(/^[A-Za-z]+$/)) {
        alert('Name must have alphabet characters only');
        document.forms["myForm"]["name"].focus();
        formIsValid = false;
    }
  
    var unit = document.forms["myForm"]["unit"].value;
    if (unit == undefined || unit == null || unit == "") {
        alert("Unit must be filled out");
        formIsValid = false;
    } else if (!unit.match(/^[0-9a-zA-Z]+$/)) {
        alert('User address must have alphanumeric characters only');
        document.forms["myForm"]["unit"].focus();
        formIsValid = false;
    }
  
    return formIsValid;
}

【讨论】:

  • Pete 非常感谢伙计,它现在可以工作了,为什么会有'!'在 ID 旁边?
  • 感叹号表示not,因此如果不匹配,则 if 是 - 它只是消除了从 if 匹配中返回 true 的需要。 More info here
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-10
  • 2014-04-09
  • 2014-01-10
  • 1970-01-01
相关资源
最近更新 更多