用户输入的Javascript验证

时间:2018-04-25 05:58:18

标签: javascript validation

尝试创建一个代码,用户必须从某个列表中输入字符串才能继续。我使用常量列出有效字符串,但我需要能够将两个值视为相等。

const VALID_STATE = ('queensland%qld%new south wales%nsw%victoria%vic%northern territory%nt%western australia%wa%south australia%sa%tasmania%tas%australian capital territory%act');

如何更改此设置以便我可以将QUEENSLAND和QLD视为相同的值,因此如果已经输入了另一个,则无效。下面是我用来验证用户输入的代码。

state = prompt('Input a state name:');
    while(VALID_STATE.indexOf(state.toLowerCase())<0){
        alert('The input state was not valid.');
        state = prompt('Re-enter the state name:');

提前致谢。

1 个答案:

答案 0 :(得分:1)

如果有人输入"nd%ql"怎么样?这不是完成这项工作的正确方法。将它们保存在Map对象中,并将"queensland"键和"qld"键映射到您选择的同名。

var stateMap = new Map([['queensland','qld'], ['qld','qld'], ['new south wales', 'nsw'], ['nsw', 'nsw'], ['victoria', 'vic'], ['vic', 'vic'], ['northern territory', 'nt'], ['nt', 'nt'], ['western australia', 'wa'], ['wa', 'wa'], ['south australia', 'sa'], ['sa', 'sa'], ['tasmania', 'tas'], ['tas', 'tas'], ['australian capital territory', 'act'], ['act', 'act']]);

var state = prompt('Enter a state.');
while (!stateMap.has(state.toLowerCase())){
  alert('The input state was not valid.');
  state = prompt('Enter a state.');
}
state = stateMap.get(state);