32172

Need help creating an html page with an external JS file that validates this format AAA.111#2222_aa-

<h3>Question</h3>

This is my html page. Im trying to validate this format AAA.111#2222_aa-1234. Im not sure whats stopping the html file from accessing the JS file. OR if my regular expression in the JS file is even correct.

<html lang = "en"> <head> <title>random</title> </head> <body> <form>

Please enter course information

<input type="text" name="userInput" id="userInput" maxlength="15"> <input type="button" value="validate" onclick="validationFunction()">

</body> </html> This is my external JS file. function validationFunction(input) { var userCourse = document.getElementById("userInput").value; var myRegularExpression = /[a-z]{3}(.\d{3})(#\d{4})(_[a-z]{2})(-\d{4})/gi; return (myRegularExpression.test(input)); } if (validationFunction(userInput)){ text = "valid"; } else { text = "invalid"; } document.getElementById("validationResults").innerHTML = text;
<h3>Answer1:</h3>

What a mess! Seems like you have all the stuff that you've learnt mixed in your mind :). Don't let this turn you down, we've all been there someday.

Well dude, let's get into your code a bit by a bit.

First of all, you need to learn something about forms; forms work when you submit and set an action with a serverside language. What actually happens when you submit a form with a GET method, it gets all the parameters that the user set in your form and calls a serverside file which you specify in the action of that form. The request in a GET case will be added to the link as query string. Let's see an example. Suppose that you set the action of the form to action="yourServersideFile.php, so this is the file that will process the request. then in your form there are two inputs with names: name and number in their tags. The request when you submit the form will be something like this: https://yourapp.com/yourServersideFile.php?name=yourname&number=yourNumber.

After submitting, the file yourServersideFile.php will process the data that has been passed to it in the query string, make the calculations, and AFTER THAT yourServersideFile.php will send the response either at the same url or will pass it to another response page that will display the results.

If you thought about that process, your page has been distroyed after clicking the submit button and sent the data to a file on the server, then the caclculations ran on the server, then the server sent you a new page.

Now let's see the first mistake in your code, you used clientside javascript to process a form. When you use javascript, all what you've built will be distroyed with the page after you submit the form except the information you might've sabed in the localStorage. So, you will never ever in the real life see a form with action="somefile.js" with the js extension unless if your backend in in Node.Js, and in this case that will even be a bad way to use Node.js. Better for you to setup an endpoint in less than a minute with Express and use AJAX to finsih all your needs without reloading the page.

Well, now we realize that we need to change the form and button to normal input and link.

Next, you have defined a function, but it will never fire as you have not set any event to trigger the function nor have you called it.

Javascript is basically an event driven language; when an even happens (typing, click, moving mouse, etc...) that triggers an event, this event triggers some functions. So, to get our function into action we need to set an event to let Javascript know that it should run this function now. So in the javascript I've added an event listener to detect a click on our link (which replaces that button).

After that you'll see the comments in the JS code attached.

So to have your code running here are the HTML and js files that your files need to run like them:

<html lang="en"> <head> <title>random</title> </head> <body> <div class="wrapper"> <label for="userCourse">Please enter your course information:</label> <input type="text" id="userCourse" name="userCourse"> <a href="#" id="my-button">New Validate</a> <p id="validationResults">

</div> <script src="validation.js"></script> </body> </html>

and your js code should be like this:

//capture the button document.addEventListener('click', (event) => { if (event.target.id === 'my-button') { //that detects a click on the button const input = document.getElementById('userCourse').value //this stores the text from the input in a variable called input const myRegularExpression = /[a-z]{3}(.\d{3})(#\d{4})(_[a-z]{2})(-\d{4})/gi // now you test the value of the input if (input) { var result = myRegularExpression.test(input) //store the test results // then display it in the p tag document.getElementById('validationResults').innerHTML = result? "valid" : "invalid" } console.log(typeof(myRegularExpression)) event.preventDefault() } })

I wish that was helpful to let you understand how it works :).

来源:https://stackoverflow.com/questions/62374411/need-help-creating-an-html-page-with-an-external-js-file-that-validates-this-for

Recommend

  • C# Extract public key from RSA PEM private key
  • How do you send emails from Angular controllers on the Mean.js stack?
  • A JNI error has occurred, while executing .jar file from command prompt
  • Corrupted files uploaded on REST method call
  • Understanding HttpServletRequest and cookies in JSF
  • Unable to select a space or join an organization on run.pivotal.io
  • what is a good structure to save this data
  • Encode string to Base64 in Inno Setup (Unicode Version of Inno Setup)
  • bootstrappedUser - Jade or EJS to HTML
  • React / Webpack - “Module parse failed: Unexpected token - You may need an appropriate loader to han
  • How can I find the difference between two times [duplicate]
  • ASP.NET MVC 3 ListBox validation
  • Parallelization via JDBC - Pyspark - How does parallelization work using JDBC?
  • how to add Image in JPanel
  • Paging Through XML Data Using jQuery and HTML
  • Override all shipping costs for a specific shipping class in Woocommerce
  • SELECT on JSONField with Django
  • Get spring boot pagination number starts from 1 instead of 0
  • Combine two jagged lists into one
  • Failed to resolve: firebase-auth-15.0.0 [closed]
  • Bundling python(“.py”)files along with java class files for a web application
  • Signed Java web start application with Glassfish 4.1 and Java7
  • Authorize Attribute Authentication with Postman in Web Api
  • Add checkbox dynamically using angular 2
  • Autocomplete source from project settings
  • How to use Flask's render_template from an ajax POST form submit
  • Thumbnails for mxml components in Flex
  • Creating 2d platforms using JavaScript
  • How to write seo friendly url's using htaccess?
  • Is there a better way for handling SpatialPolygons that cross the antimeridian (date line)?
  • How to specify generic type when the type is only known at runtime?
  • Stacked bar chart with continuous time-axis as x-axis
  • Android: Unable to detect vertical plane
  • How to integrate angular2-material (alpha 8.2) with angular2-Quickstart app
  • Debug `Unexpected end of JSON input Error` on content script
  • Apple Mach-O Linker error (“duplicate symbol”)
  • Cross compile glibc for arm, got undefined reference to some unwind functions
  • Android Library Projects on Windows and Mac
  • Angular FormGroup won't update it's value immediately after patchValue or setValue
  • How to check if object is null in Java?