简体   繁体   中英

how to validate content of text file using JavaScript?

How can i validate the content of text file using javascript? For instance i have a single text file consists of :

6594567890
6594567891
6594567892
6594567893
92345678
92345679
92345680

Accordingly, I need to validate the content with certain conditions:

  1. if its prefix is not equal to 659 and 9 then it will be rejected.
  2. if its prefix is equal to 659 but the length is not equal to 10 then it will be rejected.
  3. if its prefix is equal to 9 but the length is not equal to 8 then it will be rejected.

Currently i have the following codes using JS:

 <input type="file" name="txt_list" id="txt_list" class="inpText" size="26" /> <script> var input_file = document.getElementById('txt_list'); input_file.onchange = function() { var file = this.files[0]; var reader = new FileReader(); reader.onload = function(ev) { // Show content (ev.target === reader) alert(ev.target.result); }; reader.readAsText(file); }; </script> <font color="FF0000" style="font-weight:bolder;"> <b>* Compulsory</b>&nbsp;&nbsp;&nbsp;&nbsp; </font>

Any ideas how to do this? jsfiddle or sample codes will be highly appreciated.

Guess it is reading each line that is your concern? ev.target.result is a long chain of characters, it must be separated into string. It was not exactly clear to me how you would evaluate the lines, so bear over with that

 <input type="file" name="txt_list" id="txt_list" class="inpText" size="26" /> <script> var input_file = document.getElementById('txt_list'); input_file.onchange = function() { var file = this.files[0]; var reader = new FileReader(); reader.onload = function(ev) { var str = ''; for (var i = 0; i < ev.target.result.length; i++) { str += ev.target.result[i]; if (ev.target.result[i] == "\\n") { //new line //probably very misunderstood evaluation if (((str.substr(4, 7) == '659') && (str.length != 10)) || ((str.substr(4, 7) != '659') && (str.length == 9)) || ((str.substr(4, 5) == '9') && (str.length != 8))) { alert('rejected'); } else { alert('accepted'); } //reset the line str = ''; } } }; reader.readAsText(file); }; </script> <font color="FF0000" style="font-weight:bolder;"> <b>* Compulsory</b>&nbsp;&nbsp;&nbsp;&nbsp;</font>

JS can't access the file system (unless using NodeJS or similar). That said, you just need to write a few regexps or maybe even a simple if/else if/else conditions matching the length and the first few numbers (according to your requirements).

Example:

var a = "659000000"
if ( a.match(/^659/) && a.length == 9 ) {
    //it starts with 659 and length is 9!
}else if ....

}else....

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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