用户输入正确的验证后,没有警报消息(javascript)

时间:2017-10-27 03:49:04

标签: javascript validation

用户进入该字段后按"检查表单"假设是一个提示用户的popout帮助消息而不是它只是转到下一页。

在用户验证后,它没有显示任何警告信息的代码有什么问题?

我试图以这样的方式制作它,以便每个字段在验证后都会收到提醒



function formValidation() {
	var firstname = document.getElementById('firstname');
 	var zip = document.getElementById('zip');
	var state = document.getElementById('state');
 	var username = document.getElementById('username');
 	var email = document.getElementById('email'); 
	
	if(isAlphabet(firstname, "Please enter only letters for first name")){
		if(isNumeric(zip, "Please enter only a valid zip code")){
			if(madeSelection(state, "Please choose a state")){
				if(lengthRestriction(username, 6, 8)){
					if(emailValidator(email, "Please enter a valid email address.")){
						alert("The following information has been entered: \n"+document.getElementById('firstname').value);
						return true;
					}
				}
			}
		}
	}
	return false;
}

function notEmpty(elem, helperMsg){
	if(elem.value.length == 0){
		alert(helperMsg);
		elem.focus(); 
		return false;
	}
	return true;
}

function isNumeric(elem, helperMsg){
	var numericExpression = /^[0-9]+$/;
	if(elem.value.match(numericExpression)){
		return true;
	}else{
			alert(helperMsg);
			elem.focus();
			return false;
	}
}

function isAlphabet(elem, helperMsg){
	var alphaExp = /^[a-zA-Z]+$/;
	if(elem.value.match(alphaExp)){
		return true;
	}else{
			alert(helperMsg);
			elem.focus();
			return false;
	}
}

function isAlphanumeric(elem, helperMsg){
	var alphaExp = /^[0-9a-zA-Z]+$/;
	if(elem.value.match(alphaExp)){
		return true;
	}else{
			alert(helperMsg);
			elem.focus();
			return false;
	}
}

function lengthRestriction(elem, min, max){
	var uInput = elem.value;
	if(uInput.length >= min && uInput.length <=max){
		return true;
	}else{
			alert("Please enter between " +min+" and " +max+" characters");
			elem.focus();
			return false;
	}
}


function madeSelection(elem, helperMsg){
	if(elem.value == "Please Choose"){
		alert(helperMsg);
		elem.focus();
		return false;
	}else{
		return true;
	}
}

function emailValidator(elem, helperMsg){
	var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
	if(elem.value.match(emailExp)){
			return true;
	}else{
			alert(helperMsg);
			elem.focus();
			return false;
	}
}
&#13;
<form onsubmit='return formValidator()' action="Lab17b.html" method="get">
First Name: <input type='text' id='firstname' name='first' /><br />
Zip Code: <input type='text' id='zip' name='zip'/><br />
State: <select id='state' name='state'>
		<option>Please Choose</option>
        <option>AL</option>
        <option>TX</option>
        <option>CA</option>
        <option>WI</option>
</select><br />
Username(6-8 characters): <input type='text' id='username' name='username' /><br />
Email: <input type='text' id='email'  name='email'/><br />
<input type='submit' value='Check Form' />
</form>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

你在onsubmit方法中给出了错误的函数名称

<form onsubmit='return formValidation()' action="Lab17b.html" method="get">

小提琴 - https://jsfiddle.net/knmajLeg/

答案 1 :(得分:0)

正如RahulB所说,你的功能名称是错误的:

formValidator vs formValidation

顺便说一句,如果您对此感兴趣,请以其他方式使用您的代码。

请记住:您的代码需要干净/逻辑/语义才能毫不费力地进行调试。

每次重复一堆代码时,请尝试制作方法。

&#13;
&#13;
  function formValidator() {

    // Notice how we can see/understand the logical of
    // the function
	
    let informationAreValid = 
            firstNameIsValid()  && 
            zipIsValid()        && 
            stateIsValid()      &&
            userNameIsValid()   &&
            mailIsValid()
    
    if ( informationAreValid )
    {
	  alert("The following information has been entered: \n"+document.getElementById('firstname').value);
    }
    return informationAreValid ;

  }

  // The core of the validation
  //
  // @param {String}     type      Type of validation ('notEmpty', etc.)
  // @param {DOMElement} elem      The field
  // @param {AnyValue}   expected  The value expected, if any
  function isConform(type, elem, expected) {
    let value = elem.value ;
    switch ( type )
    {
      case 'notEmpty':
        return value.length > 0;
      case 'isNumeric':
        return value.match(/^[0-9]+$/);
      case 'isAlphabet':
        return value.match(/^[a-zA-Z]+$/);
      case 'isAlphaNum':
        return value.match(/^[0-9a-zA-Z]+$/);
      case 'isNotEqual':
        return value != expected ;
      case 'isEqual':
        return value === expected ;
      case 'isMailValid':
        return value.match(/^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/);
      case 'isBetween':
        value = value.length ;
        return value >= expected[0] && value <= expected[1]
    }
  }

  // The checker
  //
  // We validate the values, send a alert message if information
  // is bad and focus in the field.
  //
  // @return true if value of Dom element with id +idElem+ 
  // match against the +typeValidation+ and the +expected+
  // value if any.
  // Otherwise, display an alert message and return false 
  //
  function check(typeValidation, idElem, expected, errorMsg ){
    let elem = document.getElementById( idElem ) ;
    if ( isConform(typeValidation, elem, expected) ) { return true }
    switch ( typeValidation ) {
    case 'isBetween':
      let [min, max] = expected ;
      errorMsg = eval('`'+errorMsg+'`') ;
    }
    alert(errorMsg);
    elem.focus() ;
    return false ;
  }

  // Check method of every form field
  //
  // Here's is defined the error messages
  
  function firstNameIsValid() {
    let res = check('notEmpty', 'firstname', null, "First name is required") ;
    if ( ! res ) { return false }
    return check('isAlphabet', 'firstname', "Please enter only letters for first name");
  }
  function zipIsValid(){
    return check('isNumeric', 'zip', null, "Please enter only a valid zip code") ;
  }
  function stateIsValid()
  {
    return check('isNotEqual', 'state', "Please Choose", "Please choose a state") ;
  }
  function mailIsValid()
  {
    return check('isMailValid', 'email', null, "Please enter a valid email address") ;
  }
  function userNameIsValid()
  {
    return check('isBetween', 'username', [6, 8], "Please enter between ${min} and ${max} characters") ;
  }
  
  
&#13;
<form onsubmit='return formValidator()' action="" method="get">
First Name: <input type='text' id='firstname' name='first' /><br />
Zip Code: <input type='text' id='zip' name='zip'/><br />
State: <select id='state' name='state'>
		<option>Please Choose</option>
        <option>AL</option>
        <option>TX</option>
        <option>CA</option>
        <option>WI</option>
</select><br />
Username(6-8 characters): <input type='text' id='username' name='username' /><br />
Email: <input type='text' id='email'  name='email'/><br />
<input type='submit' value='Check Form' />
</form>
&#13;
&#13;
&#13;