简体   繁体   English

用户输入的Javascript验证

[英]Javascript validation of user input

Trying to make a code where the user must input a string from a certain list to proceed. 尝试创建一个代码,用户必须从某个列表中输入一个字符串才能继续。 I am using a constant to list the valid strings however I need to be able to have two values be seen as equal. 我使用常量列出有效字符串,但我需要能够将两个值视为相等。

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');

How can I change this so that I can make QUEENSLAND and QLD be seen as the same value and therefore one is not valid if the other has already been entered. 如何更改此设置以便我可以将QUEENSLAND和QLD视为相同的值,因此如果另一个已经输入,则无效。 Below is the code I'm using to validate the user input. 下面是我用来验证用户输入的代码。

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:');

Thanks in advance. 提前致谢。

How about if someone enters "nd%ql" ..? 如果有人输入"nd%ql"怎么样? This is not the right way to do this job. 这不是完成这项工作的正确方法。 Keep them in a Map object and map both "queensland" key and "qld" key to the same name of your choice. 将它们保存在Map对象中,并将"queensland"键和"qld""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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM